【问题标题】:How to add a property to a c# class at runtime如何在运行时向 c# 类添加属性
【发布时间】:2014-06-27 10:34:30
【问题描述】:

我为我的PropertyGrid 控件创建了一个类,看起来像这样:

public class DetailFilterProperties 
{
    public DetailFilterProperties(TreeViewEventArgs e)
    {
              ...
    }

    [CategoryAttribute("Base"), DescriptionAttribute("Filtered fields referring to a formatted yam field"), ReadOnly(true)]
    public Dictionary<String, String> FilteredFields
    {
        get;
        set;
    }

    ...
}

在运行时,我想向我的班级添加一个字符串属性(或字符串列表),谁能给我一个如何做到这一点的例子。

我浏览了网络并阅读了有关 ExpandoObject 的信息,但我敢打赌有一种更简单的方法可以实现这一点,但我还没有找到示例。

提前感谢您的帮助。

【问题讨论】:

  • 是否可以在您要解决的问题中使用动态对象?

标签: c# propertygrid


【解决方案1】:

您不能实际上在运行时向 C# 类添加属性;然而,PropertyGrid 通常通过ICustomTypeDescriptor 尊重灵活类型。您可以通过直接实现该接口(大量工作)或注册TypeDescriptionProvider(也需要大量工作)来提供自定义类型描述符。在任何一种情况下,您都必须实现自定义 PropertyDescriptor,并想好数据的去向。

【讨论】:

    【解决方案2】:

    您可以做的是重用我在此处对这个问题的回答中描述的 DynamicTypeDescriptor 类:PropertyGrid Browsable not found for entity framework created property, how to find it?

    像这样:

      ...
      MyDynamicClass c = new MyDynamicClass();
      c.MyStaticProperty = "hello";
    
      // build an object "type" from the original one
      DynamicTypeDescriptor dt = new DynamicTypeDescriptor(typeof(MyDynamicClass));
    
      // get a wrapped instance
      DynamicTypeDescriptor c2 = dt.FromComponent(c);
    
      // add a property named "MyDynamicProperty" of Int32 type, initial value is 1234
      c2.Properties.Add(new DynamicTypeDescriptor.DynamicProperty(dt, typeof(int), 1234, "MyDynamicProperty", null));
    
      propertyGrid1.SelectedObject = c2;
      ...
    
      // the class you want to "modify"
      public class MyDynamicClass
      {
          public string MyStaticProperty { get; set; }
      }
    

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 2019-02-15
      • 2021-08-27
      • 2013-01-03
      • 2020-10-28
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多