December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need to control the handling of the &&, ||, and ?: operators within your data type; unfortunately, these operators cannot be directly overloaded.
Overload these operators indirectly by overloading the &, |, true, and false operators, as shown in Example 3-6.
Example 3-6. Overloading &, |, true, and false
public class ObjState
{
public ObjState(int state)
{
this.State = state;
}
public int State {get; set;}
public ObjState RetObj(int state)
{
return (new ObjState(state));
}
public static ObjState operator &(ObjState obj1, ObjState obj2)
{
if (obj1 == null || obj2 == null)
throw (new ArgumentNullException("Neither object may be null."));
if (obj1.State >= 0 && obj2.State >= 0)
return (new ObjState(1));
else
return (new ObjState(-1));
}
public static ObjState operator |(ObjState obj1, ObjState obj2)
{
if (obj1.State < 0 && obj2.State < 0)
return (new ObjState(-1));
else
return (new ObjState(1));
}
public static bool operator true(ObjState obj)
{
if (obj.State >= 0)
return true;
else
return false;
}
public static bool operator false(ObjState obj)
{
if (obj.State >= 0)
return true;
else
return false;
}
public override string ToString( )
{
return State.ToString( );
}
}This technique gives you complete control over the operations of the &&, ||, and ?: operators.
public class ObjState { public ObjState(int state) { this.State = state; } public int State {get; set;} public static implicit operator bool(ObjState obj) ...Read now
Unlock full access