簡體   English   中英

具體實現的C#泛型

[英]C# Generics with concrete implementation

在C#中是否可以創建泛型方法並為給定類型添加具體實現? 例如:

void Foo<T>(T value) { 
    //add generic implementation
}
void Foo<int>(int value) {
   //add implementation specific to int type
}

在您的具體示例中,您不需要這樣做。 相反,您只需實現非泛型重載,因為編譯器更喜歡將其用於泛型版本。 編譯時類型用於調度對象:

void Foo<T>(T value) 
{ 
}

void Foo(int value) 
{
   // Will get preferred by the compiler when doing Foo(42)
}

但是,在一般情況下 ,這並不總是有效。 如果混合繼承或類似,您可能會得到意想不到的結果。 例如,如果您有一個實現IBarBar類:

void Foo<T>(T value) {}
void Foo(Bar value) {}

你通過以下方式調用它:

IBar b = new Bar();
Foo(b); // Calls Foo<T>, since the type is IBar, not Bar

您可以通過動態調度解決此問題:

public void Foo(dynamic value)
{
    // Dynamically dispatches to the right overload
    FooImpl(value);
}

private void FooImpl<T>(T value)
{
}
private void FooImpl(Bar value)
{
}

暫無
暫無

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

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