在C#
中,使用泛型参数来修改泛型方法的行为通常是一种不好的做法吗?
例如:
class Foo { }
class Bar { }
void GenericMethod<T>()
{
if (typeof(T) == typeof(Foo))
{
Console.WriteLine("execute action for Foo");
}
if (typeof(T) == typeof(Bar))
{
Console.WriteLine("execute action for Bar");
}
}
void NonGenericMethod(Type type)
{
if (type == typeof(Foo))
{
Console.WriteLine("execute action for Foo");
}
if (type == typeof(Bar))
{
Console.WriteLine("execute action for Bar");
}
}
抛开性能差异不谈,这两种方法的效果是一样的。
我想知道的是,使用泛型参数来修改方法的行为(进行分支)是否是一个好主意。这可以被认为是副作用吗?