【问题标题】:In C#, how can I select the correct overload based on a generic argument?在 C# 中,如何根据泛型参数选择正确的重载?
【发布时间】:2022-12-09 19:46:13
【问题描述】:
// overloads
void f(int x){}
void f(float x){}

// generic
void s<T>(T t){
  f(t); // <<< cannot convert from 'T' to 'int'
}

// use
s(10);

C# 编译器响应说,在s&lt;T&gt; 的正文中,我cannot convert from 'T' to 'int'。还有另一种方法可以弥合通用 - >过载差距吗?

【问题讨论】:

  • 在哪个 C#/dotnet 中? ... T 只是数字吗?
  • 从 c# 11 开始,通用数学是允许的,除了你需要一些解决方法。
  • workaround 不完全是,但你应该明白了

标签: c# generics overload-resolution


【解决方案1】:

解决此问题的一种方法是对泛型类型参数使用类型约束.这允许您指定必须是整数漂浮,这将允许编译器选择正确的重载F基于类型的函数.

以下是如何使用类型约束来解决此问题的示例:

// overloads
void f(int x){
  Console.WriteLine("int overload called");
}
void f(float x){
  Console.WriteLine("float overload called");
}

// generic
void s<T>(T t) where T : int, float{
  f(t); // <<< calls the correct overload based on the type of T
}

// use
s(10); // prints "int overload called"
s(10.0f); // prints "float overload called"

在这个例子中,函数使用类型约束来指定必须是整数漂浮.这允许编译器选择正确的重载F基于类型的函数当。。。的时候F函数在函数体内被调用s<T>.

当你打电话给带有 int 参数的函数 (小号(10)), 的类型被推断为整数, 所以整数超载的F函数被调用。同样,当您使用浮点参数调用 s 函数时 (小号(10.0f)), 的类型被推断为漂浮, 所以漂浮超载的F函数被调用。

请务必注意,类型约束是一种编译时功能,因此它们不会在您的代码中造成任何额外的运行时开销。它们只是向编译器提供额外的信息,以帮助它选择正确的函数重载。

【讨论】:

  • 停止使用 ChatGTP
猜你喜欢
  • 2021-11-14
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-14
  • 2023-03-09
相关资源
最近更新 更多