0

I am implementing a dynamic code execution in C# which allows users to write their own c# for that particular application.

I am using C# code compiler for executing the dynamic codes. The C# compiler reads the code file and construct the code in new namespace (a complete new code), compiles and runs it. In other view the base application host all these.

I have few methods that are present in host application that I want to be executed by the dynamic code. Is there any way by which the method of other namespace or application can be executed?

4

3 回答 3

1

为了使动态代码能够调用静态代码上的方法,您必须在编译动态代码时提供所需的参考。

详细信息:

假设您有一个MyClass要从动态代码访问的类。将MyClass类放在一个单独的程序集中,我们称之为MyAssembly. 编译动态代码时,其中一个属性ICodeCompiler允许您提供程序集作为引用。因此,您应该typeof(MyClass).Assembly通过该属性提供。

现在,当您编译代码时,它将能够执行以下操作:

MyClass.CallSomeMethod();

命名空间在这里不是问题。您可以确保动态代码使用完整的类型名称(例如MyNameSpace.MyClass,或者您可以using MyNamespace;在动态代码的开头生成 a。

最后,我加入了 Richard 的建议,即定义一个清晰的接口,动态代码可以使用该接口。您只需在编译时提供包含此接口的程序集作为参考。

于 2010-12-21T12:34:13.767 回答
1

你能强迫你的脚本作者实现一个接口,或者你甚至可以用你自己的实现来包装他们的代码..

就像是

public interface IMyApplication
{
      void DoSomethingInMyMainApp();
}
public interface IScriptKiddie
{
      void Init(IMyApplication app);
}

然后您的 l33t 脚本编写者可以编写

public class MyScript : IScriptKiddie //< you could emit this yourself
{

     public void Init(IMyApplication app) //<could emit this yourself if scripter knows app keyword
     {
          app.DoSomethingInMyMainApp();
     }
}

并且在您的应用程序中,您可以提供 IMyApplication 的具体实现,以便在编译、构造类然后传递给 Init 方法时传递给该类。

于 2010-12-21T12:18:38.090 回答
0

您可以使用反射。像这样的东西:

Type objType = null;
objType = _Assemblies.GetType(className);
MethodInfo methodInfo = null;
methodInfo = objType.GetMethod(TheCommandString);
methodInfo.Invoke(objType, userParameters); 
于 2010-12-21T12:36:14.330 回答