简体   繁体   中英

C# Generics with concrete implementation

Is it possible in C# to create a generic method and add also a concrete implementation for given type? For example:

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

In your specific example you wouldn't need to do this. Instead, you'd just implement a non-generic overload, since the compiler will prefer using that to the generic version. The compile time type is used to dispatch the object:

void Foo<T>(T value) 
{ 
}

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

However, in a general case , this doesn't always work. If you mix in inheritance or similar, you may get unexpected results. For example, if you had a Bar class that implemented IBar :

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

And you called it via:

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

You can work around this via dynamic dispatching:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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