Class to return a value when it is being referred
I have a class with two strings in it.
I would like to return one string when ever the object is referred to.
Code snippet:
public class ABC
{
public string A = "first";
public string B = "second";
}
public class useABC
{
ABC obj;
if(obj == "first")
Console.writeLine("True");
}
What should I do in my ABC
class to print "True".
Thanks in ad开发者_JAVA技巧vance.
You can override the implicit or explicit operator. Here's an MSDN article.
Note that too many implicit overloads can lead to a confusing or hard to use class.
I think you are looking to override the equality operator (==). Here's how to do it: Remember you have to overload the operator in both orders. Also, the compiler requires that you overload != at the same time.
public class ABS
{
public string A;
public string B;
public static bool operator ==(ABS obj, string val){return obj.A == val;}
public static bool operator !=(ABS obj, string val){return obj.A != val;}
public static bool operator ==(string val, ABS obj){return obj.A == val;}
public static bool operator !=(string val, ABS obj){return obj.A != val;}
}
The following code returns true for both expressions:
ABS abs = new ABS();
abs.A = "What?";
Assert.IsTrue(abs == "What?"); // true
Assert.IsTrue("What?" == abs); // true
How about implementing IEquatable<string>
such that you can write ABC.Equals("first")
.
public class ABS : IEquatable<string>
{
string A, B;
public bool Equals(string other)
{
return A.Equals(other) || B.Equals(other);
}
}
and later
if( ABC.Equals("first") ) { Console.WriteLine("true"); }
Then you can also override the ==
operator, but it is not recommended for class types. Like with string
it is recommended to use the .Equals()
method to check for equality. Alternatively, you can just add a method bool Contains(string other)
to check if string is in A
or B
.
精彩评论