How can I evaluate C# code dynamically?

后端 未结 16 2260
[愿得一人]
[愿得一人] 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:25

    I was trying to get a value of a structure (class) member by it's name. The structure was not dynamic. All answers didn't work until I finally got it:

    public static object GetPropertyValue(object instance, string memberName)
    {
        return instance.GetType().GetField(memberName).GetValue(instance);
    }
    

    This method will return the value of the member by it's name. It works on regular structure (class).

提交回复
热议问题