具体实现的C#泛型

Seb*_*idz 3 c# generics

在C#中是否可以创建泛型方法并为给定类型添加具体实现?例如:

void Foo<T>(T value) { 
    //add generic implementation
}
void Foo<int>(int value) {
   //add implementation specific to int type
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 6

在您的具体示例中,您不需要这样做.相反,您只需实现非泛型重载,因为编译器更喜欢将其用于泛型版本.编译时类型用于调度对象:

void Foo<T>(T value) 
{ 
}

void Foo(int value) 
{
   // Will get preferred by the compiler when doing Foo(42)
}
Run Code Online (Sandbox Code Playgroud)

但是,在一般情况下,这并不总是有效.如果混合继承或类似,您可能会得到意想不到的结果.例如,如果您有一个Bar实现的类IBar:

void Foo<T>(T value) {}
void Foo(Bar value) {}
Run Code Online (Sandbox Code Playgroud)

你通过以下方式调用它:

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

您可以通过动态调度解决此问题:

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

private void FooImpl<T>(T value)
{
}
private void FooImpl(Bar value)
{
}
Run Code Online (Sandbox Code Playgroud)