在没有多线程的情况下,C#中是否可以使(a==1 && a==2 && a==3)为true?

7

我知道可以用JavaScript实现

但是在C#中是否有可能在不使用多线程的情况下按照以下条件打印"Hurraa"?

if (a==1 && a==2 && a==3) {
    Console.WriteLine("Hurraa");
}

1
a的类型是什么?它是一个局部变量、字段还是属性? - Jacob Krall
4个回答

22

当然可以重载operator ==来做任何你想做的事情。

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var a = new AlwaysEqual();
            Assert.IsTrue(a == 1 && a == 2 && a == 3);
        }

        class AlwaysEqual
        {
            public static bool operator ==(AlwaysEqual c, int i) => true;
            public static bool operator !=(AlwaysEqual c, int i) => !(c == i);
            public override bool Equals(object o) => true;
            public override int GetHashCode() => true.GetHashCode();
        }
    }
}

3
与JavaScript相比,在C#中做到这一点非常容易。 - Salman A
@SalmanA 是啊,我总是有点惊讶 JavaScript 允许你改变toStringvalueOf的行为以及window的属性,但却没有运算符重载的概念。 - Jacob Krall
@JacobKrall,^^ 还没有。 - Nina Scholz
这比JS要多很多行 - carkod
@carkod:怎么会呢?class AlwaysEqual只有五行代码(其中两行是不必要的);在被接受的JavaScript答案中,const a = {只有三行代码。其他所有内容都是为了证明它能正常工作而进行的测试。 - Jacob Krall

20

当然,这与一些JavaScript答案的概念相同。您在属性获取器中具有副作用。

private static int _a;
public static int a { get { return ++_a; } set { _a = value; } }
static void Main(string[] args)
{
    a = 0;
    if (a == 1 && a == 2 && a == 3)
    {
        Console.WriteLine("Hurraa");
    }
    Console.ReadLine();
}

2
当然,你实际上并不需要赋值a = 0,而且你可以完全省略a内的set访问器。只有在你想要一个更短的代码示例时才需要这样做。 - Jeppe Stig Nielsen

3

这取决于a是什么。我们可以创建一个类,使其实例的行为就像上面显示的那样。我们需要做的就是重载运算符“==”和“!=”。

    class StrangeInt
    {
        public static bool operator ==(StrangeInt obj1, int obj2)
        {
            return true;
        }

        public static bool operator !=(StrangeInt obj1, int obj2)
        {
            return false;
        }
    }


    static void Main(string[] args)
    {
        StrangeInt a = new StrangeInt();
        if(a==1 && a==2 && a==3)
        {
            Console.WriteLine("Hurraa");
        }
    }

3

使用属性的C#

static int a = 1;
static int index
{
    get
    {                
        return (a++);
    }
}

static void Main(string[] args)
{
    if (index == 1 && index == 2 && index == 3)
        Console.WriteLine("Hurraa");
}

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