【问题标题】:Can I implement an implicit 'conversion' from string to boolean in C#?我可以在 C# 中实现从字符串到布尔值的隐式“转换”吗?
【发布时间】:2015-04-12 03:54:17
【问题描述】:

有什么方法可以使用 C# 实现从 stringbool隐式转换?

例如我的字符串str 的值为Y,当我尝试转换(转换)为boolean 时,它必须返回true

【问题讨论】:

  • bool b = str == "Y";
  • @NadiaChirkova,不!我的意思是:当我做 bool b = (boolean) str;
  • 不,你不能那样做。
  • 有一个 Boolean.Parse(myString) 和 Boolean.TryParse(myString) 但仅当字符串为“True”或“False”时才有效
  • 在检查之前尝试替换您的字符串。

标签: c# .net type-conversion extension-methods implicit-conversion


【解决方案1】:

没有。您不能创建用户定义的转换,这些转换既不能转换成声明的类型,也不能转换成声明的类型。

您可以轻松获得的最接近的方法是扩展方法,例如

public static bool ToBoolean(this string text)
{
    return text == "Y"; // Or whatever
}

然后你可以使用:

bool result = text.ToBoolean();

但您不能将其设为隐式转换 - 即使您可以,为了便于阅读,我还是建议您不要这样做。

【讨论】:

    【解决方案2】:

    这是一个可用于任何字符串的扩展方法。

    public static bool ToBoolean(this string input)
    {
        var stringTrueValues = new[] { "true", "ok", "yes", "1", "y" };
        return stringTrueValues.Contains(input.ToLower());
    }
    

    以下是使用此扩展方法的示例:

    Console.WriteLine("y".ToBoolean());
    

    结果将是True

    【讨论】:

      【解决方案3】:

      您需要自己制作该方法。没有办法只将字符串转换为布尔值。我相信,如果字符串不为空,你最终会得到 true。只需创建一个布尔方法,如果传递的字符串为 y,则返回 true,否则返回 false

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-15
        • 2012-07-12
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 2016-10-18
        • 1970-01-01
        • 2018-11-05
        相关资源
        最近更新 更多