我怎样才能创建这样的课程:
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!");
}
我不确定这是否可能。
答案 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")