试图将类的实例直接与字符串进行比较

时间:2013-01-14 15:17:22

标签: c# string operator-overloading

我怎样才能创建这样的课程:

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!");
}

我不确定这是否可能。

1 个答案:

答案 0 :(得分: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")