通過(guò)New-Object創(chuàng)建新對(duì)象
如果使用構(gòu)造函數(shù)創(chuàng)建一個(gè)指定類型的實(shí)例對(duì)象,該類型必須至少包含一個(gè)簽名相匹配的構(gòu)造函數(shù)。例如可以通過(guò)字符和數(shù)字創(chuàng)建一個(gè)包含指定個(gè)數(shù)字符的字符串:
代碼如下:
PS C:Powershell> New-Object String(‘*',100)
*******************************************************************************
*********************
為什么支持上面的方法,原因是String類中包含一個(gè)Void .ctor(Char, Int32) 構(gòu)造函數(shù)
代碼如下:
PS C:Powershell> [String].GetConstructors() | foreach {$_.tostring()}
Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, System.Text.Encoding)
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char[])
Void .ctor(Char, Int32)
通過(guò)類型轉(zhuǎn)換創(chuàng)建對(duì)象
通過(guò)類型轉(zhuǎn)換可以替代New-Object
代碼如下:
PS C:Powershell> $date="1999-9-1 10:23:44"
PS C:Powershell> $date.GetType().fullName
System.String
PS C:Powershell> $date
1999-9-1 10:23:44
PS C:Powershell> [DateTime]$date="1999-9-1 10:23:44"
PS C:Powershell> $date.GetType().FullName
System.DateTime
PS C:Powershell> $date
1999年9月1日 10:23:44
如果條件允許,也可以直接將對(duì)象轉(zhuǎn)換成數(shù)組
代碼如下:
PS C:Powershell> [char[]]"mossfly.com"
m
o
s
s
f
l
y
.
c
o
m
PS C:Powershell> [int[]][char[]]"mossfly.com"
109
111
115
115
102
108
121
46
99
111
109
加載程序集
自定義一個(gè)簡(jiǎn)單的C#類庫(kù)編譯為Test.dll:
代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace Test
{
public class Student
{
public string Name { set; get; }
public int Age { set; get; }
public Student(string name, int age)
{
this.Name = name;
this.Age = age;
}
public override string ToString()
{
return string.Format("Name={0};Age={1}", this.Name,this.Age);
}
}
}
在Powershell中加載這個(gè)dll并使用其中的Student類的構(gòu)造函數(shù)生成一個(gè)實(shí)例,最后調(diào)用ToString()方法。
新聞熱點(diǎn)
疑難解答
圖片精選