简体   繁体   中英

How to create properties dynamically?

I need to create properties dynamically.
My scenario is like this:
I have many classes that derive from BaseClass. BaseClass has a dictionary where inherited classes should define stuff. Those definitions are done like this.

public string Type 
{
    get 
    {
        return dictionary["type"];
    }
    set
    {
        dictionary["type"] = value;
    }
}

I will have many inherited methods like this in my derived classes, where the name of the property is almost identical to the key that references its corresponding value in the dictionary. So my idea is to add attributes in the derived classes, starting with an underscore, to distinguish them and use them to create those properties.

  1. How would I define dynamically those properties at run-time?
  2. Is it possible to define those at compile-time? Would it make sense to do so?

Unless am missing something. You can do something like this with ExpandoObject .

dynamic obj = new ExpandoObject();
obj.Type = "123";//Create Type property dynamically
Console.WriteLine(obj.Type);//Access dynamically created Type property

You can create functions dynamically as follows,

Expression<Func<int, int, string>> exp = (x, y) => (x + y).ToString();
var func = exp.Compile();
Console.WriteLine(func.Invoke(2, 3));

Also you can put them in a dictionary and use them dynamically.

Expression<Func<int, int, string>> expSum = (x, y) => (x + y).ToString();
Expression<Func<int, int, string>> expMul = (x, y) => (x*y).ToString();
Expression<Func<int, int, string>> expSub = (x, y) => (x - y).ToString();

Dictionary<string, Expression<Func<int, int, string>>> myExpressions =
    new Dictionary<string, Expression<Func<int, int, string>>>();

myExpressions.Add("summation", expSum);
myExpressions.Add("multiplication", expMul);
myExpressions.Add("subtraction", expSub);

foreach (var myExpression in myExpressions)
{
    Console.WriteLine(myExpression.Value.Compile().Invoke(2, 3));
}

To build those at compile-time under the hood (no C# behind it), see PostSharp (it allows you to define custom patterns)

But to "create" new functions, you may be interested in:

  • Expression.Compile to create delegates (dynamic methods, which are garbage collectible in .net 4.5) Pros: that's still C#. Cons: That does not allow creating types.

  • Reflection.Emit (in .Net framework) or Mono.Cecil (thirdparty) if you want to emit dynamic types or methods at runtime. Using this, a solution to your question would be to define your properties as abstract, and dynamically create a type (at runtime) which inherits from you abstract class defined in C#, an implements it automatically. Pros: VERY powerfull. Cons: You have to learn IL :)

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