布尔类型对应System.Numerics.IBitwiseOperators的等价接口是什么?
问题解答
布尔类型的逻辑非操作(!)对应的等价接口是**ILogicalNotOperators<TSelf, TResult>**,该接口定义在System.Numerics命名空间下,专门用于支持逻辑非运算的类型,bool类型已实现此接口。
你可以修改泛型函数的约束,通过这个接口确保传入类型支持!操作,避免运行时错误:
using System.Numerics; T Not<T>(T value) where T : ILogicalNotOperators<T, T> { return !value; }
修改后,委托赋值与调用可正常编译执行:
Func<bool, bool> d = Not<bool>; bool x = true; x = d(x); // x 会被修改为 false
如果你的项目基于.NET 7之前的版本,由于该接口尚未引入,可手动定义等效接口实现约束:
public interface ILogicalNot<TSelf> where TSelf : ILogicalNot<TSelf> { static abstract TSelf operator !(TSelf value); } // 为bool类型适配自定义接口的运算符逻辑 public static class BoolLogicalNotSupport { public static bool operator !(bool value) => !value; } // 使用自定义接口作为泛型约束 T Not<T>(T value) where T : ILogicalNot<T> { return !value; }
内容的提问来源于stack exchange,提问作者Brendan Lynn
相关产品推荐
相关产品推荐

