簡體   English   中英

如何通過第一個泛型參數推導出第二個泛型參數?

[英]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
}

現在我想按如下方式調用foofoo<Test>() 但是對於上面的代碼,它不起作用,因為顯然我需要指定兩個參數:

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

有什么方法可以使foo<Test>()工作 - 最好不必通過Test實例? 編譯器應該能夠推斷出U (在這種情況下為int )。

不,語言不提供。 什么你想要的語言提供的是一個結構,它可以讓你得到的保持UT<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM