具有具体实现的C#泛型 [英] C# Generics with concrete implementation

查看:67
本文介绍了具有具体实现的C#泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)
}

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

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)
{
}

这篇关于具有具体实现的C#泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆