How can I evaluate C# code dynamically?

后端 未结 16 2155
[愿得一人]
[愿得一人] 2020-11-22 03:37

I can do an eval(\"something()\"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

An example of what I

16条回答
  •  没有蜡笔的小新
    2020-11-22 04:12

    You might check the Heleonix.Reflection library. It provides methods to get/set/invoke members dynamically, including nested members, or if a member is clearly defined, you can create a getter/setter (lambda compiled into a delegate) which is faster than reflection:

    var success = Reflector.Set(instance, null, $"Property{i}", value);
    

    Or if number of properties is not endless, you can generate setters and chache them (setters are faster since they are compiled delegates):

    var setter = Reflector.CreateSetter($"Property{i}", typeof(type which contains "Property"+i));
    setter(instance, value);
    

    Setters can be of type Action but instances can be different at runtime, so you can create lists of setters.

提交回复
热议问题