首页 > 解决方案 > 如何检查泛型类中枚举集的值?

问题描述

我正在寻找检查泛型类中设置的枚举的值。当我尝试编写基本的 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

标签: c#.net

解决方案


无法使用该运算符,因为您有类型不匹配。编译无法知道 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);
    }
}

在线试用

资源:


推荐阅读