簡體   English   中英

如何在C#中調用泛型重載方法

[英]How to call generic overloaded method in C#

對C#和泛型不是很熟悉,因此我可能會缺少一些明顯的東西,但是:

鑒於:

public interface IA { }

public interface IB
{  void DoIt( IA x );
}

public class Foo<T> : IB where T : IA
{
    public void DoIt( IA x )
    {  DoIt(x); // Want to call DoIt( T y ) here
    }

    void DoIt( T y )
    {  // Implementation
    }
}

1)為什么方法void DoIt(T y)滿足接口IB要求的DoIt方法實現?

2)如何從DoIt( IA x )內調用DoIt(T y) DoIt( IA x )

1)因為任何T 都是 IA (這是由約束給出的),但並非每個IA 都是 T

class A : IA {}
class B : IA {}

var foo_b = new Foo<B>();
var a = new A();

// from the point of IB.DoIt(IA), this is legal;
// from the point of Foo<B>.DoIt(B y), passed argument is not B
foo_b.DoIt(a);

2)如果確定xT ,則使用強制轉換:

public void DoIt( IA x )
{  
    DoIt((T)x);
}

如果x可以是任意值,並且DoIt(T)是可選的,請as

public void DoIt( IA x )
{  
    DoIt(x as T);
}

void DoIt( T y )
{
    if (y == null)
        return;

    // do it
}

否則,您可以根據特定的用例引發異常或考慮其他方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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