通過New-Object創建新對象
如果使用構造函數創建一個指定類型的實例對象,該類型必須至少包含一個簽名相匹配的構造函數。例如可以通過字符和數字創建一個包含指定個數字符的字符串:
代碼如下:
PS C:Powershell> New-Object String(‘*',100)
*******************************************************************************
*********************
為什么支持上面的方法,原因是String類中包含一個Void .ctor(Char, Int32) 構造函數
代碼如下:
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)
通過類型轉換創建對象
通過類型轉換可以替代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
如果條件允許,也可以直接將對象轉換成數組
代碼如下:
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
加載程序集
自定義一個簡單的C#類庫編譯為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中加載這個dll并使用其中的Student類的構造函數生成一個實例,最后調用ToString()方法。
新聞熱點
疑難解答