0

我怎样才能制作这样的课程:

public class Foo
{
    private string m_value;
    public string Value { get { return m_value; } set { m_value = value; } }
    public Foo()
    {
        m_value = "";
    }
}

可以直接与字符串进行比较,而无需访问它的.Value属性,这样我就可以做到:

Foo m_foo = new Foo();
m_foo = "someString";

if(m_foo == "someString")
{
    Console.Writeline("It Worked!");
}

我不确定这是否可能。

4

1 回答 1

1

您可以重载 == 运算符(编译器还要求您重载 '!='、'Equals' 和 'GetHashCode')

public class Foo
{
  private string m_value;
  public string Value { get { return m_value; } set { m_value = value; } }
  public Foo()
  {
    m_value = "";
  }

  public override bool Equals(object obj)
  {
    return this.Value == obj.ToString();
  }

  public override int GetHashCode()
  {
    return Value.GetHashCode();
  }

  public static bool operator ==(Foo a, string b)
  {
    return a.Value == b;
  }

  public static bool operator !=(Foo a, string b)
  {
    return a.Value != b;
  }
}

我不确定所有这些努力是否值得,当你可以写:

if(m_foo.Value == "someString")
于 2013-01-14T19:39:36.283 回答