【问题标题】:C# set properties by name in string of Field listC#在字段列表的字符串中按名称设置属性
【发布时间】:2013-02-10 22:09:43
【问题描述】:

我用这段代码得到所有对象实例:

 Type type = this.GetType();
 FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic |
                                     BindingFlags.Instance);  

但我无法更改按钮的属性,例如 Enabled 因为SetValue 获取实例类的目标,而我没有这个。我只有班级的名称和类型。 现在如何更改字段中存在的对象的属性(启用)。

【问题讨论】:

  • 您的实例是this。您正在从该类的实例中获取您的类型。
  • 更改不存在的东西的Enabled 属性没有任何意义。您能否详细说明您正在尝试做什么以及为什么?
  • 重申@PaulSasik 如果您正在查看的类型是this 实例的类型,那么您的实例将是this

标签: c# reflection properties


【解决方案1】:

尝试稍微修改您的反射代码。一方面,您必须同时引用对象和您特别想要的 property。请记住,PropertyField 不同。

MyObject.GetType().GetProperty("Enabled").SetValue(MyObject, bEnabled, null);

您使用 MyObject 的任何类型,无论是按钮还是表单或其他类型...然后通过名称 Enabled 引用属性,然后将其设置回 MyObject

如果您想事先获取属性,可以将实例存储在变量中,但请再次记住,属性不是字段。

PropertyInfo[] piSet = MyObject.GetType().GetProperties();

您可以使用this 来获取属性集,但如果this 与您尝试启用/禁用的控件不是同一Type,则不建议使用。

添加编辑

在重新阅读了这个问题后,我明白了这一点:您似乎想要的是多层反射和泛型。您要查找的控件是附加到“this”的字段。你能做的就是沿着这些思路。

Type theType = this.GetType();
FieldInfo[] fi = theType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach ( FieldInfo f in fi)
{
    //Do your own object identity check
    //if (f is what im looking for)
    {
        Control c = f.GetValue(this) as Control;
        c.Enabled = bEnabled;
    }
    //Note: both sets of code do the same thing
    //OR you could use pure reflection
    {
        f.GetValue(this).GetType().GetProperty("Enabled").SetValue(f.GetValue(this), bEnabled, null);
    }
}

【讨论】:

    【解决方案2】:

    首先,您实际上是在使用对象的字段。如果你真的想要可写的属性,那么你想要这样的东西:

    PropertyInfo[] properties = type.GetProperties(Public | SetProperty | Instance);
    

    一旦你有了它,你的 enabled 属性可能会这样设置:

    myenabledPropertyInfo.SetValue(targetObject, value, null);
    

    其中 targetobject 是我们感兴趣的 Enabled 属性的对象,value 是我们希望分配的值(在这种情况下,可能是布尔值...)

    希望对您有所帮助...

    【讨论】:

      猜你喜欢
      • 2012-08-11
      • 2019-03-12
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 2013-04-24
      相关资源
      最近更新 更多