简体   繁体   English

C#中带有类型参数的泛型类型

[英]Generic types with type parameter in C#

I don't think that this could be done in C#, but posting this just to make sure. 我不认为这可以在C#中完成,但发布这个只是为了确保。 Here's my problem. 这是我的问题。 I would like to do something like this in C#: 我想在C#中做这样的事情:

var x = 10;
var l = new List<typeof(x)>();

or 要么

var x = 10;
var t = typeof(x);
var l = new List<t>();

But of course this doesn't work. 但当然这不起作用。 Although this shouldn't be a problem as the type t is resolved at compile time. 虽然这不应该是一个问题,因为类型t在编译时被解析。 I understand that this can be solved with reflection, but as types are known at compile time using reflection would be overkill. 我知道这可以通过反射来解决,但是在编译时使用反射知道类型会是过度的。

public static List<T> CreateCompatibleList<T> (T t)
{
    return new List<T> () ;
}

var x = 10 ;
var l = CreateCompatibleList (x) ;

You're trying to get .Net to set a generic type using a run-time operator. 您正试图让.Net使用运行时运算符设置泛型类型。 As you know, that won't work. 如你所知,那是行不通的。 Generics types must be set at compile time. 必须在编译时设置泛型类型。

Defining generics is done like this in C#: 在C#中这样定义泛型:

var someList = new List<int>();

You can not define generics like this: 不能像这样定义泛型:

var x = 1;
var someType = typeof(x);
var someList = new List<someType>();

because you're specifying the type at run time in this case, not compile time. 因为在这种情况下你是在运行时指定类型,而不是编译时。 C# doesn't support that. C#不支持这一点。

You can't do it exactly how you are asking, but with a little reflection you can accomplish the same thing 你无法完全按照自己的要求去做,但通过一点反思,你就可以完成同样的事情

Type genericType = typeof(List<>);
Type[] type = new Type[] { typeof(int) };
Type instanceType = genericType.MakeGenericType(type);
object instance = Activator.CreateInstance(instanceType );
var l = (List<int>)instance;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM