我有一个在类上有属性的类,但是我只希望能够在内部设置其值,但允许在其上使用public获取访问器。由于在C#这样的类中没有PS等效项:
public class ModelParser<T> {
//Properties and fields here
public async Task Export(/*File or InputStream*/){
//Read items from database? and write to file
}
public async Task<ICollection<T>> Import(/*File or InputStream or JSON string*/)
{
//Import here to database?
return items;
}
}
我已经考虑在类上实现以下变通办法,以使“私有”成员对属性的公共访问者保持隐藏:
public string PropertyName {
get;
private set;
}
这很好并且可以实现我想要的功能,但是该类还具有几个静态属性,我希望通过其静态构造函数执行相同的操作。虽然上面的代码确实可以来设置类类型本身的属性(用class MyClass {
hidden [string]$_PropertyName
MyClass( $propertyValue ) {
$this._PropertyName = $PropertyValue
$this | Add-Member -ScriptProperty -Name 'PropertyName' -Value {
return $this.$_PropertyName
} -SecondValue {
throw "Cannot write value to a readonly property"
}
}
}
代替[MyClass]
),但是有一个小怪癖使得访问“只读”属性与通常访问的静态成员不一致:
$this
我可以访问hidden static [string]$_StaticProperty = 'someValue'
static MyClass() {
[MyClass] | Add-Member -ScriptProperty StaticProperty -Value {
return [MyClass]::$_StaticProperty
}
}
,但只能访问它是实例成员:
StaticProperty
是否可以使用[MyClass]::StaticProperty # ==> $null
[MyClass].StaticProperty # ==> someValue
向类型添加 static 成员,以便使访问器语法保持一致?
答案 0 :(得分:1)
是否有一种方法可以使用Add-Member将静态成员添加到类型中,以便使访问器语法保持一致?
Add-Member
旨在允许用户在 instance 对象中添加合成ETS属性-在任何人考虑将class
关键字添加到语言语法之前的一段时间
换一种说法,在ETS中,“静态成员”的含义为零,因为ETS成员与已实例化的对象的 identity 相关。
如果您希望使用C#中的类成员行为,请使用C#:
Add-Type @'
public class MyClass
{
static MyClass()
{
MyClass.StaticProperty = "some value";
}
public static string StaticProperty { get; private set; }
}
'@
# Use [MyClass]::StaticProperty