How can I evaluate C# code dynamically?

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

    Not really. You can use reflection to achieve what you want, but it won't be nearly as simple as in Javascript. For example, if you wanted to set the private field of an object to something, you could use this function:

    protected static void SetField(object o, string fieldName, object value)
    {
       FieldInfo field = o.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
       field.SetValue(o, value);
    }
    

提交回复
热议问题