【发布时间】:2012-02-07 03:51:17
【问题描述】:
我希望能够调用具有 Nullable 参数的通用 foo 方法。当 Foo 方法的主体调用 Foo() 时,它会递归,导致堆栈溢出(没有 .com)。有没有办法让 if 语句中的调用使用运行时类型调用正确的重载?
我知道更改名称会做到这一点,并且我理解为什么会发生递归,但不知道另一种写法。
感谢收看。
class Program {
static void Main(string[] args) {
int? x = 5;
int y = 10;
Foo(x, y);
}
static void Foo<T>(Nullable<T> arg, T defaultValue) where T : struct {
if (arg.HasValue)
Foo(arg.Value, defaultValue);
}
static void Foo(int arg, int defaultValue) {
Console.WriteLine(string.Format("I'm an int arg={0}, default={1]}", arg, defaultValue));
}
static void Foo(string arg, int defaultValue) {
Console.WriteLine(string.Format("I'm an string arg={0}, default={1]}", arg, defaultValue));
}
static void Foo(bool arg, int defaultValue) {
Console.WriteLine(string.Format("I'm an double arg={0}, default={1]}", arg, defaultValue));
}
}
【问题讨论】:
-
您希望
double?去哪里? -
尝试在调用 Foo() 时显式转换参数
标签: c# .net generics overloading nullable