c# - 如何在给定类名的情况下获取用户定义的对象类型?

标签 c# generics

如果我将用户定义对象的类名作为字符串,我如何在泛型函数中将它用作对象的类型?

SomeGenericFunction(objectID);

最佳答案

如果你有一个字符串,那么首先要做的是使用 Type.GetType(string),或者(最好)Assembly.GetType(string) 来获取 Type 实例。从那里开始,您需要使用反射:

Type type = someAssembly.GetType(typeName);
typeof(TypeWithTheMethod).GetMethod("SomeGenericFunction")
          .MakeGenericMethod(type).Invoke({target}, new object[] {objectID});

其中 {target} 是实例方法的实例,null 是静态方法。

例如:

using System;
namespace SomeNamespace {
    class Foo { }
}
static class Program {
    static void Main() {
        string typeName = "SomeNamespace.Foo";
        int id = 123;
        Type type = typeof(Program).Assembly.GetType(typeName);
        object obj = typeof(Program).GetMethod("SomeGenericFunction")
            .MakeGenericMethod(type).Invoke(
                null, new object[] { id });
        Console.WriteLine(obj);
    }
    public static T SomeGenericFunction<T>(int id) where T : new() {
        Console.WriteLine("Find {0} id = {1}", typeof(T).Name, id);
        return new T();
    }
}

关于c# - 如何在给定类名的情况下获取用户定义的对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/811294/

相关文章:

c# - 静态类的线程安全

c# - 在 LINQ 中使用 “OfType”

java - 如何编写一个通过hibernate插入而没有任何依赖的通用类

c# 3.0 转换接口(interface)泛型类型

c# - Unity 为非泛型接口(interface)注册泛型类型

c# - 重命名命名空间后找不到为 Main 方法指定的 'WindowsFormsApplication1.Program'

javascript - ASP.Net Core 回发后如何保持选项卡处于事件状态

c# - 通过覆盖插件 nopCommerce 3.3 中的 GenericPathRoute.cs 更改 URL 路由

c# - WPF 字符串数组 - 绑定(bind)到资源

swift - 在 Swift 中,如何使用泛型扩展协议(protocol)?