[英]Use switch with type Class in generic method
Is it possible to use the switch when comparing Classes in a generic method? 在通用方法中比较类时是否可以使用开关? Example:
例:
switch (typeof(T))
{
case typeof(Class1):
// ...
break;
case typeof(Class2):
// ...
break;
default:
break;
}
The idea is not to use the name but the Class object. 这个想法不是使用名称,而是使用Class对象。 At moment I'm using:
此刻我正在使用:
if (typeof(T) == typeof(Class1))
{
// ...
}
else if (typeof(T) == typeof(Class2))
{
// ...
}
For simplicity, it would be good to use the switch. 为了简单起见,最好使用该开关。
In cases like this, I use dictionaries, paired with values of lambdas as fit for the specific problem at hand. 在这种情况下,我使用字典,将lambda值配对以适合当前的特定问题。
var options = new Dictionary<Type, Action>()
{
{ typeof(string), () => doSomething() },
{ typeof(int), () => doSomething() },
...
};
Action act = null;
if (options.TryGetValue(typeof(T), out act) {
act();
} else {
// default
}
The dictionary is usually a static readonly
field or property, so the indexing is done just once. 字典通常是
static readonly
字段或属性,因此索引仅执行一次。
In your specific case you can get along with a Dictionary<Type, Func<object, string>>
, like so: 在您的特定情况下,您可以使用
Dictionary<Type, Func<object, string>>
,如下所示:
private static readonly Formatters = new Dictionary<Type, Func<object, string>>()
{
{ typeof(Class1), o => ((Class1)o).format() },
{ typeof(Class2), o => FormatClass.FormatClass2((Class2)o) },
...
};
T instance;
string formatted = Formatters[typeof(T)](instance);
If you are using C# 7, you can make use of pattern matching. 如果使用的是C#7,则可以使用模式匹配。
For example, 例如,
public void Method<T>(T param)
{
switch(param)
{
case var _ when param is A:
Console.WriteLine("A");
break;
case var _ when param is B:
Console.WriteLine("B");
break;
}
}
Where 哪里
public class A{}
public class B{}
Expanding on Anu Viswan 's answer , Since C# 7.1, this is valid: 从C#7.1开始扩展Anu Viswan的答案 ,这是有效的:
public void Method<T>(T param)
{
switch (param)
{
case A a:
Console.WriteLine("A");
break;
case B b:
Console.WriteLine("B");
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.