gpt4 book ai didi

c# - 运算符 '|' 不能应用于类型 'System.Enum' 和 'System.Enum' 的操作数

转载 作者:太空狗 更新时间:2023-10-29 21:12:51 25 4
gpt4 key购买 nike

我可以|&enum,但不是Enum。为什么是这样?有没有办法解决?我正在尝试为 WPF 编写枚举标志转换器。

public class EnumFlagConverter : IValueConverter
{
public Enum CurrentValue;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var theEnum = value as Enum;
CurrentValue = theEnum;
return theEnum.HasFlag(parameter as Enum);
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
Enum CurrentValue;
var theEnum = parameter as Enum;
if (CurrentValue.HasFlag(theEnum)) //this line is allowed
return CurrentValue &= ~theEnum; //~theEnum not allowed, neither is the &=
else
return CurrentValue |= theEnum; // |= cannot be applied to Enum and Enum
}
}

最佳答案

Why is this?

在编译器知道枚举的基础类型的情况下,编译器可以毫无问题地执行按位运算。在编译器不知道底层类型的情况下,它无法知道您是否需要 8 位、16 位、32 位,甚至可能是 64 位操作,而只是完全放弃。另请注意,编译器无法知道您的两个枚举值都不是 null,并且编译器无法知道这两个枚举值具有相同的类型甚至宽度。

Is there any way around this?

您可以知道,您永远不会处理大于 64 位的枚举,并且 64 位操作将产生正确的结果,即使对于此处的 8 位枚举类型也是如此。因此,您可以通过将操作显式编写为 64 位操作来帮助编译器。

static Enum Or(Enum a, Enum b)
{
// consider adding argument validation here

if (Enum.GetUnderlyingType(a.GetType()) != typeof(ulong))
return (Enum)Enum.ToObject(a.GetType(), Convert.ToInt64(a) | Convert.ToInt64(b));
else
return (Enum)Enum.ToObject(a.GetType(), Convert.ToUInt64(a) | Convert.ToUInt64(b));
}

对于 And 也是如此。

关于c# - 运算符 '|' 不能应用于类型 'System.Enum' 和 'System.Enum' 的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24172370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com