c# - 如何检查泛型类中枚举集的值?
问题描述
我正在寻找检查泛型类中设置的枚举的值。当我尝试编写基本的 if 语句if (item.Value == AlphaType.A1)
时,出现以下错误:
运算符“==”不能应用于“T”和“Program.AlphaType”类型的操作数
这是代码:
public enum AlphaType
{
A1,
A2
}
public enum BetaType
{
B1,
B2
}
public class Item<T>
{
public T Value { get; set; }
public string Foo { get; set;}
}
public static void Main()
{
var item1 = new Item<AlphaType> { Value = AlphaType.A1, Foo = "example 1" };
var item2 = new Item<BetaType> { Value = BetaType.B1, Foo = "example 2" };
PrintAlphaFoo(item1);
PrintAlphaFoo(item2);
}
public static void PrintAlphaFoo<T>(Item<T> item)
{
if (item.Value == AlphaType.A1)
{
Console.WriteLine(item.Foo);
}
}
这里的代码应该输出example 1而不是example 2。
解决方案
无法使用该运算符,因为您有类型不匹配。编译无法知道 T 是您的枚举。您可以通过将值转换为对象然后再次转换为您的类型来修复它:
if ((AlphaType)(object)item.Value == AlphaType.A1)
或者我们甚至可以让 Equals 为我们的演员表写:
if (item.Value.Equals(AlphaType.A1))
但你不能停在这里。您的错误已修复,但不是您的主要问题。只有这样,示例 2将被打印。您必须在之前进行另一次检查:
if (item.Value.GetType() == typeof(AlphaType) && (AlphaType)(object)item.Value == AlphaType.A1)
完整代码:
public enum AlphaType
{
A1,
A2
}
public enum BetaType
{
B1,
B2
}
public class Item<T>
{
public T Value { get; set; }
public string Foo { get; set;}
}
public static void Main()
{
var item1 = new Item<AlphaType> { Value = AlphaType.A1, Foo = "example 1" };
var item2 = new Item<BetaType> { Value = BetaType.B1, Foo = "example 2" };
PrintAlphaFoo(item1);
PrintAlphaFoo(item2);
}
public static void PrintAlphaFoo<T>(Item<T> item)
{
if (item.Value.GetType() == typeof(AlphaType) && item.Value.Equals(AlphaType.A1))
{
Console.WriteLine(item.Foo);
}
}
资源:
推荐阅读
- javascript - 获取输入值并添加到另一个
- python - PyTorch 前向传播在相同样本上返回不同的 logits
- c# - C# 程序在朋友的 PC 上立即关闭
- c# - 如何检查节点的存在和具有特定属性的节点是否存在?
- activemq-artemis - 在 docker 上集群 Artemis 的问题
- ios - 本地主机上的开发 node.js 服务器在 swiftUI 应用程序中返回 nil,但在浏览器中不返回
- python - 如何将具有不同数字的小时/分钟列转换为 python/pandas 中的日期时间对象?
- vim - 是否可以在 vim 缩写 id 中包含回车?
- r - 如何为对数正态分布列绑定蒙特卡罗模拟结果?
- sql - 使用 SQL 请求复制行和编辑值,但需要改进一下