【发布时间】:2019-02-06 12:40:42
【问题描述】:
在泛型方法中比较类时是否可以使用开关? 示例:
switch (typeof(T))
{
case typeof(Class1):
// ...
break;
case typeof(Class2):
// ...
break;
default:
break;
}
这个想法不是使用名称而是使用 Class 对象。 目前我正在使用:
if (typeof(T) == typeof(Class1))
{
// ...
}
else if (typeof(T) == typeof(Class2))
{
// ...
}
为简单起见,最好使用开关。
【问题讨论】:
-
C# v7.1 模式开关对您没有帮助:
An expression of type 'T' cannot be handled by a pattern of type 'Class1'。我认为您的if / else if模式与您将获得的一样好 -
create a string which depends on the Class properties, which again can vary from Class1 to Class2.这些字符串是什么样的?您应该考虑将该逻辑添加到类(Class1等)本身中,而不是添加到此方法中。然后这个方法可以调用你添加到Class1/Class2等的方法(如果你有一个定义方法的接口更好,每个类都实现)。 -
@ptuga 您是否将 C# 版本与 .NET 版本混为一谈?
-
原始副本在 .NET 4.5 @ptuga - stackoverflow.com/a/42488315/34092 上运行良好 - 模式匹配只是语法糖。您使用的是什么 IDE?
-
@ptuga 假设 Visual Studio 2017+,那么使用 C# 7 应该没问题。语言版本不会影响您的框架目标。