class GenericWrapper<T>
{
}
class WrapperInstance : GenericWrapper<string>
{
}
class Usage
{
public static Usage Create<T1, T2> (T2 t2) where T1 : GenericWrapper<T2>
{
return null;
}
}
...
// works
Usage.Create<WrapperInstance, string>("bar");
// doesnt work
Usage.Create<WrapperInstance>("bar");
我怀疑答案是否定的,但有没有办法让最后一行编译通过?
我希望编译器强制我提供一个字符串参数,而不必知道或先去检查 WrapperInstance
看什么T
的 GenericWrapper
它实现了。
我知道我可以通过使用第一种方法或采用 object
来编译它。作为参数并进行运行时检查,但这不是问题;)我在很大程度上怀疑这是我唯一的两个选择。
谢谢
最佳答案
I suspect the answer is no, but is there a way I can make the last line compile?
没有。 Create
有两个通用类型参数。您可以不指定任何内容,也可以同时指定两者。在没有的情况下,编译器将尝试从调用参数推断类型。但是,在这种情况下它不能,因为 T1
从未出现在参数列表中。因此,您必须同时指定两者。
关于c# - 编译时泛型语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5650203/