无法从程序集中加载类型

时间:2019-03-02 05:26:07

标签: c# .net-assembly appdomain

我正在研究MSDN MarshalByRefObject中的这段代码,不知道为什么会引发异常。我在想,是否可能是Worker类型与Program类位于同一程序集中?我是否需要在GAC中安装此程序集,尽管我正在Visual Studio 2017编辑器中以调试模式运行此程序集。我对如何使用汇编不了解。

using System;
using System.Reflection;

namespace AppDomainMarshalByRefObject
{

    public class Program
    {
        public static void Main(string[] args)
        {
            Worker localWorker = new Worker();
            localWorker.PrintDomain();

            AppDomain ad = AppDomain.CreateDomain("New domain");
            Worker remoteWokrer = (Worker)ad.CreateInstanceAndUnwrap(typeof(Worker).Assembly.FullName, "Worker");

            remoteWokrer.PrintDomain();
            Console.ReadKey();
        }
    }

    public class Worker : MarshalByRefObject
    {
        public void PrintDomain()
        {
            Console.WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain.CurrentDomain.FriendlyName);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您实例化了不完整的typename。将此添加到您的代码中:

public static void Main(string[] args)
    {
        ...

        var typeName = typeof(Worker);

        AppDomain ad = AppDomain.CreateDomain("New domain");
        Worker remoteWokrer = (Worker)ad.CreateInstanceAndUnwrap(typeof(Worker).Assembly.FullName, typeName.FullName);

        ...
    }