c# - 如何覆盖 TryParse?

标签 c# types overriding

我想覆盖 boolTryParse 方法来接受"is"和“否”。我知道我想使用的方法(如下),但我不知道如何覆盖 bool 的方法。

... bool TryParse(string value, out bool result)
{
    if (value == "yes")
    {
        result = true;
        return true;
    }
    else if (value == "no")
    {
        result = false;
        return true;
    }
    else
    {
        return bool.TryParse(value, result);
    }
}

最佳答案

您不能覆盖静态方法。但是,您可以创建一个扩展方法。

public static bool TryParse(this string value, out bool result)
{
    // For a case-insensitive compare, I recommend using
    // "yes".Equals(value, StringComparison.OrdinalIgnoreCase); 
    if (value == "yes")
    {
        result = true;
        return true;
    }
    if (value == "no")
    {
        result = false;
        return true;
    }

    return bool.TryParse(value, out result);
}

把它放在一个静态类中,然后像这样调用你的代码:

string a = "yes";
bool isTrue;
bool canParse = a.TryParse(out isTrue);

关于c# - 如何覆盖 TryParse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3023681/

相关文章:

c# - 用 Func 替换 MongoDB 查询中的 lambda 表达式

c# - 在 Repository/UnitOrWork 之上使用服务类时,我应该将逻辑不适合 Repository 的常用数据访问代码放在哪里?

c# - C#中的自动类型转换

c++ - 如何为一个虚函数提供多个覆盖

Python重写类(非实例)特殊方法

c# - MVVM-如何在文本框中选择文本?

c# - 便携类 4.0 : Missing Features

iOS:在 didSelectRowAtIndexPath 方法中解析选定行的 url

c++ - 如何在 C++ 中将 typedef 与类初始值设定项参数一起使用?

.net - 是否有小于字节的 .NET 数据类型?