简体   繁体   中英

How to add a property to a c# class at runtime

I created a class for my PropertyGrid control which looks something like this:

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;
    }

    ...
}

At runtime i want to add a string property (or a list of strings) to my class can anyone give me an example of how to do this please.

I browsed the web and read about ExpandoObject but i bet there is an easier way to achieve this, I just didnt find an example yet.

thanks for your help in advance.

You can't actually add a property to a C# class at runtime; however, PropertyGrid usually respects flexible types via ICustomTypeDescriptor . You can supply a custom type descriptor either by implementing that interface directly (lots of work), or by registring a TypeDescriptionProvider (also lots of work). In either case, you'll have to implement a custom PropertyDescriptor , and think of somewhere for the data to go.

What you could do is reuse the DynamicTypeDescriptor class described in my answer to this question here on SO: PropertyGrid Browsable not found for entity framework created property, how to find it?

like this:

  ...
  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; }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM