[英]How to deduce the second generic parameter through the first generic parameter?
我有以下几点:
interface IGeneric<T> {}
class Test : IGeneric<int> {}
// in an unrelated class
public void foo<T, U>()
where T : IGeneric<U>
{
// do something
}
现在我想按如下方式调用foo
: foo<Test>()
。 但是对于上面的代码,它不起作用,因为显然我需要指定两个参数:
Using the generic method 'MainClass.foo<T,U>()' requires 2 type arguments
有什么方法可以使foo<Test>()
工作 - 最好不必通过Test
实例? 编译器应该能够推断出U
(在这种情况下为int
)。
不,语言不提供。 什么你想要的语言提供的是一个结构,它可以让你得到的保持U
从T<U>
如
public void foo<T> : where exists U : T is IGeneric<U>
public void foo<IGeneric<U>>()
但是通用语法并没有那么复杂。 最近的将是以下之一:
public void foo<U>( IGeneric<U> t = null)
public void foo<U>( Test t = null)
哪些不是你想要的?
您可以使用额外的接口定义在代码中执行此操作:
internal interface IGeneric { }
interface IGeneric<T> : IGeneric { }
public void foo<T>() where T : IGeneric
{
var tGenericU= typeof(T)
.GetInterfaces()
.Where( i=>
i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IGeneric<>) )
.FirstOrDefault();
Debug.Assert(typeofU != null);
var typeofU= tGenericU.GetGenericArguments().First();
// do something
Console.WriteLine( typeofU );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.