I do not remember how to do in C# a comparison of a class against a primitive type.
Example
public class Validate{
... //This is here that we would need to add code
//if I remember to开发者_C百科 make the object act as a boolean for example
}
...
Validate v = new Validate(...);
if(v==true)
{
...
}
Do you know the name of that and how to do it?
I think you're looking for an implicit type conversion.
Add the following method to your Validate class:
public static implicit operator bool(Validate v)
{
// Logic to determine if v is true or false
return true;
}
To do what you want, you need to override the implicit cast operator:
public class MyObject
{
private int i;
public MyObject(int i)
{
this.i = i;
}
public static implicit operator bool(MyObject o)
{
return o.i % 2 == 0;
}
}
The above example will evaluate to true if the field i
is even:
MyObject o1 = new MyObject(1);
MyObject o2 = new MyObject(2);
if (o1)
{
Console.WriteLine("o1");
}
if (o2)
{
Console.WriteLine("o2");
}
The output of the above is o2
.
However, it is a bit of a horrible implementation as it leads to confusing code in that you have constructs that read as if (object)
, which would be unfamiliar to most readers - if (object.IsValid)
makes the intention much more clearer.
do you mean operator overloading?
public static bool operator == (Validate v, bool value)
{
return /* some comparison */
// or going off of the other posters answer
return v.IsValid == value;
}
Just add an IsValid
property to your Validate
class and call that property:
public class Validate
{
public bool IsValid
{
get { [implementation here] }
}
}
...
Validate v = new Validate(...);
if(v.IsValid)
{
...
}
It is possible to create an implicit operator, but it is not advisable to use it this way, because it would make your code hard to follow for other developers.
UPDATE
Okay, just for completeness and education, this is how to do it:
public class Validate
{
public bool IsValid
{
get { [implementation here] }
}
public static implicit operator bool(Validate v)
{
return v.IsValid;
}
}
But again, don't do it. It would make your code pretty hard to follow.
精彩评论