且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中使用泛型动态对象

更新时间:2023-01-16 08:54:10

你将无法直接创建一个类的强类型实例,因为编译器没有足够的信息来知道封闭的泛型类型是什么。



您可以创建一个后期绑定的实例使用反射的类型:

You won't be able to directly create a strongly-typed instance of the class, as the compiler doesn't have enough information to know what the closed generic type is.

You can create a late-bound instance of the type using reflection:
Type t = obj.GetType();
Type myType = typeof(ClassA<>).MakeGenericType(t);
object instance = Activator.CreateInstance(myType);



或者您可以使用反射来调用创建和使用实例的通用方法:


Or you can use reflection to call a generic method to create and use the instance:

static class Helper
{
    private static readonly MethodInfo DoStuffMethod = typeof(Helper).GetMethod("DoStuffHelper", BindingFlags.NonPublic | BindingFlags.Static);
    
    private static void DoStuffHelper<T>(T value)
    {
        var instance = new ClassA<T>();
        ...
    }
    
    public static void DoStuff(object value)
    {
        if (value == null) throw new ArgumentNullException(nameof(value));
        
        Type t = value.GetType();
        MethodInfo m = DoStuffMethod.MakeGenericMethod(t);
        m.Invoke(null, new[] { value });
    }
}