在类ctor中以编程方式设置公共属性 [英] Programmatically Setting Public Property in Class Ctor

查看:40
本文介绍了在类ctor中以编程方式设置公共属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 PowerShell V5.0 中以编程方式在类的构造函数中设置公共属性.测试类有许多公共属性需要根据传递给类的构造函数的对象进行填充(亲切地称为$something")

I want to programmatically set a public property within a class' constructor in PowerShell V5.0. The test class has many public properties that are to be filled in depending on the object passed to the class' constructor (lovingly referred to as '$something')

我认为如果我创建一个可访问的公共属性名称数组并遍历它们会节省大量代码,因为设置公共属性的值只是在 $something 对象上调用相同的方法传递给它.

I thought it'd save a lot of code if I created an array of public property names which was accessible and iterate through them, as the setting the value of the public properties is just calling the same method on the $something object passed to it.

尝试在每个作用域上使用 Set-Variable cmdlet(我认为它是本地作用域).可以在构造函数中手动设置每个公共属性,但如果可能的话,我希望能够缩短它.

Tried using the Set-Variable cmdlet on every scope (I thought it'd be local scope). It could be done manually setting each public property in the constructor, but I'd love to be able to shorten it if possible.

    Class TestClass
    {
        [STRING]$PublicProperty
        [STRING]$PublicProperty1
        ... ... ... #Loads more properties
        [STRING]$PublicProperty50
        #An array that contains name for public properties
        [ARRAY]$ArrayOfPublicProperties = @("PublicProperty", "PublicProperty1"...)

        TestClass($something)
        {
            foreach ($property in $this.ArrayOfPublicProperties)
            {
                Set-Variable -Name "$($property.Name)" -Scope Local -Value $($something.GetValue(#blablabla))
            }
        }
    }

我希望能够遍历公共数组(这是粗略的代码,但它适用于我所处的情况,我不知道想任何其他方法)并使用 Set 设置变量- 变量 cmdlet.相反,它没有设置任何东西.我确定我过去做过类似的事情,以编程方式创建和设置变量等...... idk.

I expect to be able to iterate through the public array (it's gross code, but it works for the situation I'm in and I don't know enough to think of any other ways) and set the variable using the Set-Variable cmdlet. Instead it doesn't set anything. I'm sure I've done something similar in the past, programmatically creating and setting variables etc... idk.

请帮忙

推荐答案

Set-Variable 仅适用于常规变量,不适用于属性.

Set-Variable only works with regular variables, not with properties.

您必须通过 .psobject.properties 使用反射,这也不需要 $ArrayOfPublicProperties 辅助属性:

Class TestClass
{
    [string]$PublicProperty
    [string]$PublicProperty1
    # ...

    TestClass($something)
    {
        # Loop over all properties of this class.
        foreach ($prop in $this.psobject.Properties)
        {
          $prop.Value = $something.GetValue(#blablabla)
        }
    }
}

<小时>

但是请注意,PowerShell 允许通过从 hashtable(自定义)对象强制转换的方式方便地构造和初始化对象 具有匹配属性.


Note, however, that PowerShell conveniently allows constructing and initializing objects by a way of a cast from a hashtable or (custom) object that have matching properties.

注意事项:要使其发挥作用:

  • 该类必须具有无构造函数(即,隐式仅支持无参数的默认构造函数),
  • OR,如果有构造函数:

  • the class must either have NO constructor (i.e., implicitly support only the parameter-less default constructor),
  • OR, if there are constructors:

  • 无参数构造函数也必须存在.
    • 症状,如果该条件不满足:类型转换错误:Cannot convert ... to type ...
    • a parameter-less constructor must exist too.
      • Symptom, if that condition isn't met: a type-conversion error: Cannot convert ... to type ...
      • 症状,如果不满足该条件:调用单参数构造函数.

      输入哈希表/对象的属性名称集必须是目标类属性的子集;换句话说:输入对象不能包含目标类中不存在的属性,但不是所有目标类属性都必须存在..>

    • The set of property names of the input hashtable / object must be a subset of the target class' properties; in other words: the input object mustn't contain properties that aren't also present in the target class, but not all target-class properties must be present.

      应用于您的示例(请注意,不再有显式构造函数,因为原始构造函数 TestClass($something) 由于 $something 会破坏该功能> 隐式 [object]- 类型):

      Applied to your example (note that there's no longer an explicit constructor, because the original constructor, TestClass($something), would defeat the feature, due to $something being implicitly [object]- typed):

      Class TestClass
      {
          [string]$PublicProperty
          [string]$PublicProperty1
          # ...
          # Note: NO (explicit) constructor is defined.
      }
      
      # Construct a [TestClass] instance and initialize its properties
      # from a hashtable, using a cast.
      [TestClass] @{ PublicProperty = 'p0'; PublicProperty1 = 'p1'}
      

      这篇关于在类ctor中以编程方式设置公共属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆