基于带有C#的泛型类型参数的条件代码
问题描述:
我在C#中有一个方法,该方法接收一个泛型类型作为参数:
I have a method in C# which receives a generic type as argument:
private void DoSomething<T>(T param)
{
//...
}
我需要根据 param
的类型执行不同的操作.我知道我可以用几个 if
句子来实现它,就像这样:
I need to perform different things depending on what type is param
of. I know I can achieve it with several if
sentences, like this:
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
或其他我不知道的方法?
Is there a better way of doing this? Maybe with switch-case
or another approach that I'm not aware of?
答
您可以为特定类型创建特定方法.
You can create a specific method for a particular type.
private void DoSomething<T>(T param)
{
//...
}
private void DoSomething(int param) { /* ... */ }
private void DoSomething(string param) { /* ... */ }