如何从类型的名称和程序集的名称加载类型

时间:2011-11-21 17:23:35

标签: c# reflection

我需要获取一个类型的实例,其名称和程序集名称将在运行时具有。我事先知道该类型将具有无参数构造函数。最简单的方法是什么?

这比我希望的那样难以接受。

编辑:我不是,如果这是相关的,但会引用程序集。我不需要从磁盘或其他东西加载它。

7 个答案:

答案 0 :(得分:6)

答案 1 :(得分:5)

来自MSDN

  

Activator.CreateInstance方法(字符串,字符串)

     

使用命名的程序集和默认构造函数创建指定了其名称的类型的实例。

public static ObjectHandle CreateInstance(
  string assemblyName,
  string typeName
)

示例:

var assemblyName =
    "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

var typeName = "System.Net.WebClient";

var instance = Activator.CreateInstance(assemblyName, typeName).Unwrap();

答案 2 :(得分:3)

如果引用System.Web.dll对您来说不是问题,那么鲜为人知的BuildManager.GetType Method非常有效。它甚至不需要程序集名称,因为它会扫描当前AppDomain执行路径中程序集中的类型。

所以代码是:

object instance = Activator.CreateInstance(BuildManager.GetType("MyNamespace.MyClass", true));

答案 3 :(得分:2)

以下内容应该足够了:

var assmebly = Assembly.Load("FullyQualifiedAssemblyName");
var type = assmebly.GetType("FullTypeName");
var instance = Activator.CreateInstance(type);

答案 4 :(得分:2)

Type referencedType = typeof(AReferencedType);
AReferencedType instance = Activator.CreateInstance<AReferencedType>();

or 

Type type = Type.GetType("Type's full name");
object instance = Activator.CreateInstance(type);

答案 5 :(得分:2)

Activator.CreateInstance(Type.GetType("System.Int32"));

Activator

Type

答案 6 :(得分:1)

这可以使用花哨的dynamic关键字。您需要引用另一个类来传递测试,或者使用构建事件来复制构建的DLL。

namespace TestLibrary
{
    [TestFixture]
    public class Tests
    {
        [Test]
        public void FileCheck()
        {
            dynamic otherClass = 
                AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap("OtherLibrary.dll",                
                    "Prefix.OtherLibrary.SomeClass");
            otherClass.SayHello();   // look, ma! no casting or interfaces!
        }
    }
}

namespace Prefix.OtherLibrary
{
    public class SomeClass
    {
        public void SayHello()
        {
            Console.WriteLine("Hello, world.");
        }
    }
}

Activator不同,AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap filename 作为第一个参数而不是类型说明符。这有时很有用,尤其是当您不关心程序集的强名称时。