如何动态评估 C# 代码? [英] How can I evaluate C# code dynamically?
问题描述
我可以使用 eval("something()");
在 JavaScript 中动态执行代码.有没有办法让我在 C# 中做同样的事情?
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#?
我想要做的一个例子是:我有一个整数变量(比如 i
),我有多个属性,名称分别为:Property1"、Property2"、Property3", 等等.现在,我想根据 i
的值对"Propertyi "属性执行一些操作.
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
.
使用 Javascript 这真的很简单.有没有办法用 C# 做到这一点?
This is really simple with Javascript. Is there any way to do this with C#?
推荐答案
免责声明:这个答案是在 2008 年写的.从那时起,情况发生了巨大的变化.
DISCLAIMER: This answer was written back in 2008. The landscape has changed drastically since then.
查看此页面上的其他答案,尤其是详细介绍 Microsoft.CodeAnalysis.CSharp.Scripting
的答案.
Look at the other answers on this page, especially the one detailing Microsoft.CodeAnalysis.CSharp.Scripting
.
其余的答案将保持原样,但不再准确.
Rest of answer will be left as it was originally posted but is no longer accurate.
不幸的是,C# 不是那样的动态语言.
Unfortunately, C# isn't a dynamic language like that.
但是,您可以做的是创建一个包含类和所有内容的 C# 源代码文件,然后通过 C# 的 CodeDom 提供程序运行它并将其编译为程序集,然后执行它.
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.
MSDN 上的这个论坛帖子包含一个答案,在页面下方有一些示例代码:
从字符串创建匿名方法?
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.
如果你用 ; 分割字符串首先,要获取单个属性,您可以使用以下代码为类的特定属性获取 PropertyInfo 对象,然后使用该对象来操作特定对象.
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]);
这篇关于如何动态评估 C# 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!