【问题标题】:C# : Convert an object to Boolean depending on a class variableC#:根据类变量将对象转换为布尔值
【发布时间】:2016-08-02 19:45:19
【问题描述】:

我的班级看起来像这样:

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-04-13]:

就像丹尼斯写的那样,我正在使用

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 类型

编译器不知道它应该使用布尔运算符还是 UInt64 运算符。

所以我写了

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

但是这两种类型转换是灰色的。

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

问候沃尔夫冈

顺便说一句,有没有可以测试格式及其输出的游乐场?以及如何向其他用户发送私信?

【问题讨论】:

    标签: c# object boolean compare


    【解决方案1】:

    你可以使用扩展方法来实现你可以在任何时候使用的方法,不仅仅是这个类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,因为我现在可以更改类本身:-)
    【解决方案2】:

    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 从类转换为结构(参见this 参考)。如果您决定转换它,请避免使用可变结构。

    【讨论】:

    • 虽然看起来我可以将类更改为结构,但我的原始类必须保持类类型而不是结构类型,因为它具有更多将 TestClass 分类为类的属性、字段和方法: -)
    • 我在 VS 2010 中编写了我的示例,但是从 Unity 中可用的 VS2015 社区版中,我知道隐式转换运算符会检查对象是否为空!?那么什么实现会优先呢?
    • 演员操作员不会为您检查任何内容。如果AMethod 将返回null,则操作员将抛出NRE,而不进行空值检查。您可以轻松地对其进行测试。
    • 我的意思是,写 String s = null; if (s) {} 等于 if (!String.IsNullOrEmpty(s)) {}
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多