基于 C# 泛型类型参数的条件代码
本文关键字:条件 代码 泛型类型参数 基于 | 更新日期: 2023-09-27 18:31:55
我在 C# 中有一个方法,它接收泛型类型作为参数:
private void DoSomething<T>(T param)
{
//...
}
我需要根据param
的类型执行不同的事情。我知道我可以用几句if
话来实现它,就像这样:
private void DoSomething<T>(T param)
{
if (param is TypeA)
{
// do something specific to TypeA case
} else if (param is TypeB)
{
// do something specific to TypeB case
} else if ( ... )
{
...
}
// ... more code to run no matter the type of param
}
有没有更好的方法?也许用switch-case
或其他我不知道的方法?
只需使用重载而不是泛型。
如果项目/逻辑结构允许,最好将DoSomething移动到T中并使用IDoSomething接口对其进行描述。这样你可以写:
private void DoSomething<T>(T param) where T:IDoSomething
{
param.DoSomething()
}
如果这不是一个选项,那么您可以设置规则字典
var actionsByType = new Dictionary<Type, Action<T /*if you neeed that param*/>(){
{ Type1, DoSomething1 },
{ Type2, DoSomething2 },
/..
}
在您的方法中,您可以调用:
private void DoSomething<T>(T param){
//some checks if needed
actionsByType[typeof(T)](param/*if param needed*/);
}
可以为特定类型创建特定方法。
private void DoSomething<T>(T param)
{
//...
}
private void DoSomething(int param) { /* ... */ }
private void DoSomething(string param) { /* ... */ }
如前所述,如果是一个简单的情况,请使用重载。任何更奇怪的事情,你都可以适应这个(它的快速和肮脏的道歉)。
class Program
{
interface IDoSomething<T>
{
void DoSomething(T param);
}
class Test : IDoSomething<int>, IDoSomething<string>
{
public void DoSomething(int param)
{
}
public void DoSomething(string param)
{
}
}
static void Main(string[] args)
{
DoSomething(4);
}
static void DoSomething<T>(T param)
{
var test = new Test();
var cast = test as IDoSomething<T>;
if (cast == null) throw new Exception("Unhandled type");
cast.DoSomething(param);
}
}