我一直在尝试使以下代码正常工作(所有内容都在同一个程序集中定义):
namespace SomeApp{
public class A : MarshalByRefObject
{
public byte[] GetSomeData() { // }
}
public class B : MarshalByRefObject
{
private A remoteObj;
public void SetA(A remoteObj)
{
this.remoteObj = remoteObj;
}
}
public class C
{
A someA = new A();
public void Init()
{
AppDomain domain = AppDomain.CreateDomain("ChildDomain");
string currentAssemblyPath = Assembly.GetExecutingAssembly().Location;
B remoteB = domain.domain.CreateInstanceFromAndUnwrap(currentAssemblyPath,"SomeApp.B") as B;
remoteB.SetA(someA); // this throws an ArgumentException "Object type cannot be converted to target type."
}
}
}
我要做的是将在第一个 AppDomain 中创建的“A”实例的引用传递给子域,并让子域在第一个域上执行一个方法。在“B”代码的某个点上,我将调用“remoteObj.GetSomeData()”。必须这样做,因为“GetSomeData”方法中的“byte[]”必须在第一个 appdomain 上“计算”。我应该怎么做才能避免异常,或者我该怎么做才能达到相同的结果?