动态确定类型参数后返回通用类型 [英] Return Generic Type after determining Type Parameter dynamically

查看:52
本文介绍了动态确定类型参数后返回通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的通用类

I have a generic class as shown below

public class MyClass<T>
{
    public T MyProp { get; set; }
}

现在我想返回这种类型的实例,并在运行时确定type参数,如下所示

Now I want to return the instance of this type with the type parameter being determined at run time, something as shown below

public MyClass<object> ReturnWithDynamicParameterType()
{
    //This function determines the type of T at runtime and should return instance of MyClass<T>
}

这是如何实现的

推荐答案

不可能.您可以像这样在运行时为任意通用类型参数创建通用类型

What you are trying to do is not possible. While you can create a generic type for an arbitrary generic type argument at runtime like this

public MyClass<object> ReturnWithDynamicParameterType(Type genericArgument)
{
    Type genericType = typeof(MyClass<>).MakeGenericType(genericArgument);
    return (MyClass<object>)Activator.CreateInstance(genericType);
}

return 行将始终抛出 InvalidCastException .正如李已经说过的,类是不变的.这意味着例如 MyClass< object> MyClass< string> 只是不同类型.它们彼此之间甚至没有继承.

this return line will always throw an InvalidCastException. As Lee already commented, classes are invariant. This means that for example MyClass<object> and MyClass<string> are simply not the same types. They are not even inherited from one another.

即使协方差也无济于事,因为类中的通用参数不允许使用 out 关键字.

Even co-variance won't help since the out keyword is not allowed for generic parameters in classes.

在编译时不知道类型,我看不到解决方案.但我确信,您可以解决实际上试图通过其他方法实现的目标.

I don't see a solution for this without knowing the types at compile-time. But I'm sure that you can solve what you are actually trying to achieve by other methods.

这篇关于动态确定类型参数后返回通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆