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

发布于 2024-12-17 18:16:00 字数 140 浏览 2 评论 0原文

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

这比我希望的要难得多。

编辑:我不知道这是否相关,但程序集将被引用。我不需要从磁盘或其他东西加载它。

I need to get an instance of a type whose name and assembly name I will have at runtime. I know in advance the type will have a parameterless constructor. What's the easiest way to do this?

It's waaaaaaay harder than I was hoping it would be.

Edit: I'm not if this is relevant, but the assembly will be referenced. I don't need to load it from disk or something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

卷耳 2024-12-24 18:16:01

来自 MSDN

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

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

public static ObjectHandle CreateInstance(
  字符串程序集名称,
  字符串类型名称
)

示例:

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

var typeName = "System.Net.WebClient";

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

From MSDN:

Activator.CreateInstance Method (String, String)

Creates an instance of the type whose name is specified, using the named assembly and default constructor.

public static ObjectHandle CreateInstance(
  string assemblyName,
  string typeName
)

Example:

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

var typeName = "System.Net.WebClient";

var instance = Activator.CreateInstance(assemblyName, typeName).Unwrap();
淡淡的优雅 2024-12-24 18:16:01

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

所以代码是:

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

If referencing System.Web.dll is not an issue for you, there is the little-known BuildManager.GetType Method which is quite efficient. It does not even requires the assembly name because it scans for types in assemblies in the current AppDomain execution path.

So the code would be:

object instance = Activator.CreateInstance(BuildManager.GetType("MyNamespace.MyClass", true));
一身仙ぐ女味 2024-12-24 18:16:01

以下应该足够了:

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

The following should suffice:

var assmebly = Assembly.Load("FullyQualifiedAssemblyName");
var type = assmebly.GetType("FullTypeName");
var instance = Activator.CreateInstance(type);
噩梦成真你也成魔 2024-12-24 18:16:01
Type referencedType = typeof(AReferencedType);
AReferencedType instance = Activator.CreateInstance<AReferencedType>();

or 

Type type = Type.GetType("Type's full name");
object instance = Activator.CreateInstance(type);
Type referencedType = typeof(AReferencedType);
AReferencedType instance = Activator.CreateInstance<AReferencedType>();

or 

Type type = Type.GetType("Type's full name");
object instance = Activator.CreateInstance(type);
一抹苦笑 2024-12-24 18:16:01
Activator.CreateInstance(Type.GetType("System.Int32"));

激活器

类型

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

Activator

Type

孤千羽 2024-12-24 18:16:01

这是使用花哨的 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 接受文件名作为第一个参数,而不是类型说明符。这有时很有用,特别是当您不关心程序集的强名称时。

Here's something that works using the fancy dynamic keyword. You'll need to reference the other class for the test to pass, or use a build event to copy over the built 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.");
        }
    }
}

Unlike Activator, AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap takes a filename as the first argument rather than a type specifier. This is sometimes useful, especially when you don't care about the strong name of the assembly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文