【问题标题】:C# Generics with concrete implementation具有具体实现的 C# 泛型
【发布时间】:2018-12-05 00:01:59
【问题描述】:

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

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

【问题讨论】:

  • 我已经放弃了我的答案,我也投票关闭,因为不清楚你在问什么。好像是XY problem

标签: c# generics


【解决方案1】:

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

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

【讨论】:

  • 很好的答案,里德。
猜你喜欢
  • 2019-03-19
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 2010-12-15
  • 2018-09-20
  • 1970-01-01
相关资源
最近更新 更多