是否有可能使用未绑定类型,在C#泛型类型参数? [英] Is it possible to use an unbound type as a generic type parameter in C#?
问题描述
我有一个C#泛型:
public class Generic<TParameter> { ... }
它不会出现,我可以使用未绑定类型作为类型参数。我得到错误CS1031:类型有望
当我尝试以下方法:
var lGenericInstance = new Generic<List<>>();
我如何使用未绑定类型作为泛型类型参数?是否有变通方法?我的泛型类是刚刚使用反射,所以我可以提供的类型的成员字符串列表。
How can I use an unbound type as a generic type parameter? Are there workarounds? My generic class is just using reflection so I can get a list of the provided type's members as strings.
更新:我对未绑定类型的问题已经回答了,所以我也跟进采用的单独的问题,解决我的特定问题。
Update: My question about the unbound type has been answered, so I have followed up with a separate question that addresses my specific problem.
推荐答案
试试这个:
class Foo<T> { }
class Bar<T> { }
Type unboundBar = typeof(Bar<>);
Type unboundFoo = typeof(Foo<>);
Type boundFoo = unboundFoo.MakeGenericType(new[] { unboundBar });
Console.WriteLine(boundFoo.Name);
Conosle.WriteLine(boundFoo.GetGenericArguments().First().Name);
请注意,你可以不写
Type boundFoo = typeof(Foo<Bar<>>)
由于该规范明确规定:
这是未绑定的泛型类型只能在的typeof表达(§7.6.11)
An unbound generic type can only be used within a typeof-expression (§7.6.11).
(酒吧<>
是不被用作一个参数来的的typeof表达的位置,相反,它是一个泛型类型参数的参数为的的typeof表达的。)
(Bar<>
is not being used as a parameter to the typeof-expression here, rather, it's a generic type parameter to the parameter to a typeof-expression.)
然而,这是完全合法的CLR内,如上述使用反射所示。
However, it's perfectly legal within the CLR, as the above using reflection shows.
但什么是你想怎么办?你不能有绑定类型的实例,所以我不明白这一点。
But what are you trying to do? You can't have instances of unbound types, so I don't get it.
这篇关于是否有可能使用未绑定类型,在C#泛型类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!