[英]How to create and use same class in main C# code and runtime compiled code?
My C# app uses CSharpCodeProvider.CompileAssemblyFromSource
to compile small scripts on C#. 我的C#应用程序使用
CSharpCodeProvider.CompileAssemblyFromSource
在C#上编译小型脚本。
I need a way to set many fields of main code in script. 我需要一种在脚本中设置主代码许多字段的方法。
I need something that will be visible in both places. 我需要在两个地方都能看到的东西。
I declared test class in script and main code like that: 我在脚本和主要代码中声明了测试类,如下所示:
namespace MainNS
{
public class TestClass
{
public string asd;
public int dsa;
}
}
My script looks like that: 我的脚本如下所示:
using System;
using System.Reflection;
using System.Collections.Generic;
namespace ScriptedNS
{
public class TestClass
{
public string asd;
public int dsa;
}
public class ScriptTaskInfo
{
private TestClass GlobalTC;
public void Initialize(object global_tc)
{
this.GlobalTC = (TestClass)global_tc; //of course invalid cast here
this.GlobalTC.asd = "string set from script that should be visible in main code";
}
public void Execute()
{
//do something with this.GlobalTC
}
}
}
When I create TestClass
instance in main code and try to Initialize
script object with it I getting invalid cast exception. 当我在主代码中创建
TestClass
实例并尝试使用它Initialize
脚本对象时,我得到了无效的强制转换异常。
How to achieve that same object is visible for both script and main code and I can set it's fields like normal, not just having Dictionary<string, object>
map and always casting from object to different types. 如何实现相同的对象对于脚本和主代码都是可见的,我可以将其设置为正常的字段,而不仅仅是具有
Dictionary<string, object>
映射并且始终将对象转换为不同类型。
instead of (object global_tc) you can use (dynamic global_tc) 可以使用(dynamic global_tc)代替(object global_tc)
public class ScriptTaskInfo
{
private TestClass GlobalTC;
public void Initialize(dynamic global_tc)
{
this.GlobalTC = global_tc;
this.GlobalTC.asd = "string set from script that should be visible in main code";
}
public void Execute()
{
//do something with this.GlobalTC
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.