我可以在C#中实现从字符串到布尔值的隐式"转换"吗?

LIN*_*INQ 1 .net c# extension-methods type-conversion implicit-conversion

有什么办法可以实现一个隐含的从转换stringbool使用C#?

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

Jon*_*eet 6

不能.您无法创建用户定义的转换,这些转换不会转换为它们声明的类型.

你最容易接近的将是一种扩展方法,例如

public static bool ToBoolean(this string text)
{
    return text == "Y"; // Or whatever
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

bool result = text.ToBoolean();
Run Code Online (Sandbox Code Playgroud)

但你不能把它变成一个隐含的转换 - 即使你可以,我建议你不要为了可读性.


Nik*_*tov 5

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

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

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

Console.WriteLine("y".ToBoolean());
Run Code Online (Sandbox Code Playgroud)

结果将是True