如何创建自定义类的实例返回bool?

时间:2014-08-31 13:11:12

标签: c#

someList此处将返回bool值:

List<int> someList = new List<int>();
if(someList) { }

在下面的行中,编译器会警告我说我不能隐式地将类型CustomType转换为bool

CustomType t = new CustomType();
if(customType) {}

那么,如何让我的班级实例返回bool?甚至是其他内容,例如integerfloat

1 个答案:

答案 0 :(得分:4)

在CustomType类中,您可以将隐式转换运算符定义为bool:

public static implicit operator bool(CustomType custom)
{
    return true; // Place your logic here
}

应谨慎定义隐式转换运算符,以避免不可维护的代码。我建议你考虑在CustomType类中有一个方法或属性,它根据一些逻辑返回一个布尔值:

public bool IsValid { get { return true; // Place your logic here } }