【发布时间】:2012-07-21 08:50:00
【问题描述】:
我有以下代码:
public class Class1
{
void ValueSpecific(string arg)
{
// do string stuff
}
void ValueSpecific(int arg)
{
// do int stuff
}
void ValueSpecific(float arg)
{
// do float stuff
}
void ValueGeneric(string arg)
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
void ValueGeneric(int arg)
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
void ValueGeneric(float arg)
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
void Main(string s, int i, float f)
{
ValueGeneric(s);
ValueGeneric(i);
ValueGeneric(f);
}
}
这可行,但 ValueGeneric 的所有三个重载的主体都是相同的。我想将它们合并为一种方法,如下所示:
void ValueGeneric<T>(T arg) where T: string, float, int
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
但这当然不是有效的 C#。 我能想到的最好的是:
void ValueGeneric(object arg)
{
// Do stuff
if (arg is int)
{
ValueSpecific((int)arg);
}
else if (arg is string)
{
ValueSpecific((string)arg);
}
else if (arg is float)
{
ValueSpecific((float)arg);
}
else
{
Debug.Assert(false, "Invalid type)
}
// Do more stuff
}
但这似乎很不雅。我会很感激任何建议。 (虽然我对任何解决方案都感兴趣,但 .NET3.5 支持的解决方案最好,因为我正在使用它。)
【问题讨论】:
-
如果你真的想这样做,你就不得不求助于反射。
-
扩展方法怎么样?
-
@JeffMercado 是对的。如果你想要优雅,你必须使用反射。