值类型,我有以下代码:如何使用泛型
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的支持是最好的,因为这是我在用的。)
当你确实想做到这一点,你必须诉诸使用反射。 – 2012-07-21 08:58:46
扩展方法怎么样? – 2012-07-21 09:02:06
@JeffMercado是对的。如果你想要它的优雅,你必须使用反射。 – pikzen 2012-07-21 09:04:42