How can I evaluate C# code dynamically?

2018-12-31 06:51发布

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 am trying to do is: I have an integer variable (say i) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc. Now, I want to perform some operations on the " Propertyi " property depending on the value of i.

This is really simple with Javascript. Is there any way to do this with C#?

16条回答
旧时光的记忆
2楼-- · 2018-12-31 07:20

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).

查看更多
梦该遗忘
3楼-- · 2018-12-31 07:23

You can use reflection to get the property and invoke it. Something like this:

object result = theObject.GetType().GetProperty("Property" + i).GetValue(theObject, null);

That is, assuming the object that has the property is called "theObject" :)

查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 07:26

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);
}
查看更多
余欢
5楼-- · 2018-12-31 07:26

I don't now if you absolutely want to execute C# statements, but you can already execute Javascript statements in C# 2.0. The open-source library Jint is able to do it. It's a Javascript interpreter for .NET. Pass a Javascript program and it will run inside your application. You can even pass C# object as arguments and do automation on it.

Also if you just want to evaluate expression on your properties, give a try to NCalc.

查看更多
何处买醉
6楼-- · 2018-12-31 07:26

You also could implement a Webbrowser, then load a html-file wich contains javascript.

Then u go for the document.InvokeScript Method on this browser. The return Value of the eval function can be catched and converted into everything you need.

I did this in several Projects and it works perfectly.

Hope it helps

查看更多
荒废的爱情
7楼-- · 2018-12-31 07:26

Uses reflection to parse and evaluate a data-binding expression against an object at run time.

DataBinder.Eval Method

查看更多
登录 后发表回答