C#:根据类变量将对象转换为布尔值

3

我的课程大概长这样:

public class Testclass 
{
    public int myValue;
}

在另一个情境下,我想要简单地将 myValue 的值与 0 进行比较。那么我会写如下代码:
Testclass tc = new Testclass();
tc.myValue = 13;
if (tc.myValue == 0)
{ 
}

如何简化这个过程,使得 Testclass 对象知道当它与布尔值进行比较时(或用作布尔值)应该怎么做呢?可以这样写:
Testclass tc = new Testclass();
tc.myValue = 13;
if (tc)
{
}

更准确地说,Testclass将是包含在库中另一个方法的结果,因此代码看起来像这样:
anotherClass ac =new anotherClass();
// if (ac.AMethod().myValue == 0) 
// should be
if (ac.AMethod())
{

}

方法AMethod的样子如下:

public Testclass AMethod()
{
    return new Testclass();
}

[2016年4月13日更新]:

正如Dennis所写,我正在使用

public static implicit operator bool(TestClass value)

获取我的类的“布尔值”。为了更加精确并且与实际应用更贴切,我想将签名修改为

public static implicit operator UInt64(FlexComDotNetFehler fehler)

public static implicit operator Boolean(FlexComDotNetFehler fehler)

所以,这两种类FlexComDotNetFehler的方法在第一种情况下返回内部的UInt64字段作为实际的UInt64表示,而在第二种情况下返回一个Boolean值,当UInt64值大于0时为真。

但是现在,当我编写代码时

FlexComDotNetFehler x;
FlexComDotNetFehler y;
if (x == y)

此处的x和y均为类型FlexComDotNetFehler

编译器无法确定应该使用Boolean还是UInt64运算符。

因此,我编写了以下代码:

if ((UInt64)x != (UInt64)y)

但是这两个类型转换被禁用了。

@Ɖiamond ǤeezeƦ:感谢您的重新格式化和编辑。但我认为现在我弄对了?

问候Wolfgang

顺便说一下,有没有可以测试格式和输出的游乐场?如何向其他用户发送私人消息?

2个回答

4

TestClass定义隐式转换算子:

class TestClass
{
    public int myValue;

    public static implicit operator bool(TestClass value)
    {
        // assuming, that 1 is true;
        // somehow this method should deal with value == null case
        return value != null && value.myValue == 1;
    }
}

同时考虑将 TestClass 从类转换为结构体(参见此处的参考文档)。如果您决定进行转换,请避免使用可变结构体。


尽管我似乎可以将类更改为结构体,但我的原始类必须保持类类型而不是结构体类型,因为它具有更多的属性、字段和方法,这使得 TestClass 归类为类 :-) - Wolfgang Roth
我在VS 2010中编写了我的示例,但是从Unity中可用的VS2015社区版中,我知道隐式转换运算符会检查对象是否为空!那么哪种实现会优先? - Wolfgang Roth
转换运算符不会为您检查任何内容。如果 AMethod 返回 null,则操作符将在没有进行空值检查的情况下抛出 NRE。您可以轻松测试它。 - Dennis
我的意思是,写成String s = null;if (s){}等同于if (!String.IsNullOrEmpty(s)){} - Wolfgang Roth

0

你可以使用扩展方法来实现任何时候都能使用的方法,而不仅仅是为这个类 Testclass。

  public static class IntExtension
{
    public static bool IsBool(this int number)
    {
        bool result = true;
        if (number == 0)
        {
            result = false;
        }
        return result;
    }
}

然后你可以

if ((ac.AMethod()).IsBool())
{}

有了你的建议,每次想知道结果时我需要调用.IsBool。这与我的代码中的if (ac.AMethod().myValue == 0)是一样的。 此外,我不需要扩展TestClass类,因为我现在可以直接更改该类 :-) - Wolfgang Roth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接