我期待您在泛型类设置一个枚举值。当我尝试写一个基本的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);
}
}
这里的代码应该输出实施例1但不例2。
经营者不能使用,因为你有一个类型不匹配。编译无法知道,T是你的枚举。您可以通过铸造你的价值的一个对象,然后通过再次投放到您的类型修复它:
if ((AlphaType)(object)item.Value == AlphaType.A1)
或者,我们甚至可以让等于投给我们写字:
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);
}
}
资源:
你可以一试Enum.TryParse()
类似方法
public static void PrintAlphaFoo<T>(Item<T> item)
{
AlphaType alphaType;
if (!Enum.TryParse<AlphaType>(item.Value.ToString(), out alphaType))
{
return;
}
if (alphaType == AlphaType.A1)
{
Console.WriteLine(item.Foo);
}
}