SHE*_*NeP 7 c# overriding class operators
我有以下课程:
public class InterlockedBool
{
private int _value;
public bool Value
{
get { return _value > 0; }
set { System.Threading.Interlocked.Exchange(ref _value, value ? 1 : 0); }
}
public static bool operator ==(InterlockedBool obj1, bool obj2)
{
return obj1.Value.Equals(obj2);
}
public static bool operator !=(InterlockedBool obj1, bool obj2)
{
return !obj1.Value.Equals(obj2);
}
public override bool Equals(bool obj)
{
return this.Value.Equals(obj);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我可以检查Value是否为真,没有== true?操作员覆盖有效,但是我也可以这样使用它吗?
InterlockedBool ib = new InterlockedBool();
if (ib) { }
Run Code Online (Sandbox Code Playgroud)
而不是(这有效,但通常我省略了== truein if语句.
if (ib == true) { }
Run Code Online (Sandbox Code Playgroud)
.Value =?谢谢你的帮助:)
你需要能够将您的对象转换到和从一个布尔
隐式转换
你的布尔对象:
public static implicit operator bool(InterlockedBool obj)
{
return obj.Value;
}
Run Code Online (Sandbox Code Playgroud)
然后是你对象的布尔值:
public static implicit operator InterlockedBool(bool obj)
{
return new InterlockedBool(obj);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以测试它:
InterlockedBool test1 = true;
if (test1)
{
//Do stuff
}
Run Code Online (Sandbox Code Playgroud)
显式转换
如果您希望此类的用户知道发生了转换,您可以强制显式转换:
public static explicit operator bool(InterlockedBool obj)
{
return obj.Value;
}
public static explicit operator InterlockedBool(bool obj)
{
return new InterlockedBool(obj);
}
Run Code Online (Sandbox Code Playgroud)
然后你必须显式地转换你的对象:
InterlockedBool test1 = (InterlockedBool)true;
if ((bool)test1)
{
//Do stuff
}
Run Code Online (Sandbox Code Playgroud)
编辑(由于OP评论)
在从布尔值到你的对象的转换中,我调用了一个你没有提到的构造函数,这是我将如何构建它:
public InterlockedBool(bool Value)
{
this.Value = Value;
}
Run Code Online (Sandbox Code Playgroud)
因此,值的设置是保证线程安全的
您可以定义向bool的隐式转换:
public static implicit operator bool(InterlockedBool obj)
{
return obj.Value;
}
Run Code Online (Sandbox Code Playgroud)