How can I evaluate C# code dynamically?

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

    Unfortunately, C# isn't a dynamic language like that.

    What you can do, however, is to create a C# source code file, full with class and everything, and run it through the CodeDom provider for C# and compile it into an assembly, and then execute it.

    This forum post on MSDN contains an answer with some example code down the page somewhat:
    create a anonymous method from a string?

    I would hardly say this is a very good solution, but it is possible anyway.

    What kind of code are you going to expect in that string? If it is a minor subset of valid code, for instance just math expressions, it might be that other alternatives exists.


    Edit: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here.

    If you split the string by the ; first, to get individual properties, you can use the following code to get a PropertyInfo object for a particular property for a class, and then use that object to manipulate a particular object.

    String propName = "Text";
    PropertyInfo pi = someObject.GetType().GetProperty(propName);
    pi.SetValue(someObject, "New Value", new Object[0]);
    

    Link: PropertyInfo.SetValue Method

提交回复
热议问题