简体   繁体   English

如何通过第一个泛型参数推导出第二个泛型参数?

[英]How to deduce the second generic parameter through the first generic parameter?

I have the following:我有以下几点:

interface IGeneric<T> {}

class Test : IGeneric<int> {}

// in an unrelated class
public void foo<T, U>()
    where T : IGeneric<U>
{
    // do something
}

Now I want to call foo as follows: foo<Test>() .现在我想按如下方式调用foofoo<Test>() But with the code above, it doesn't work, since apparently I need to specify both parameters:但是对于上面的代码,它不起作用,因为显然我需要指定两个参数:

 Using the generic method 'MainClass.foo<T,U>()' requires 2 type arguments

Is there any way to make foo<Test>() work - preferably without having to pass a Test instance?有什么方法可以使foo<Test>()工作 - 最好不必通过Test实例? The compiler should be able to deduce U (to int in this case).编译器应该能够推断出U (在这种情况下为int )。

No, the language doesn't offer that.不,语言不提供。 What you'd like the language to offer is a construct that lets you get hold of the U from T<U> eg什么你想要的语言提供的是一个结构,它可以让你得到的保持UT<U>

public void foo<T> : where exists U : T is IGeneric<U>
public void foo<IGeneric<U>>()

But generic syntax is not that sophisticated.但是通用语法并没有那么复杂。 The nearest would be one of these:最近的将是以下之一:

public void foo<U>( IGeneric<U> t = null)
public void foo<U>( Test t = null)

Which are not what you want?哪些不是你想要的?

You can do it in code with an extra interface definition:可以使用额外的接口定义在代码中执行此操作:

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.

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