Converter是C#中一个非常有用的概念,主要用于类型转换。它通常以委托或接口的形式出现,允许开发者定义如何将一种类型转换为另一种类型。下面我将详细介绍Converter的概念、使用场景,并以布尔型转换为例展示具体应用。
Converter的基本概念
1. Converter委托
在C#中,Converter<TInput, TOutput>
是一个泛型委托,定义在System
命名空间中。它的签名如下:
public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
这个委托表示一个方法,该方法将对象从TInput
类型转换为TOutput
类型。
2. 使用场景
Converter常用于:
-
集合类型转换
-
数据格式化
-
类型适配
-
值转换(如字符串到布尔值)
布尔型转换示例
示例1:简单的字符串到布尔值转换
// 定义转换器
Converter<string, bool> stringToBoolConverter = s =>
s.Equals("true", StringComparison.OrdinalIgnoreCase) ||
s.Equals("1", StringComparison.OrdinalIgnoreCase) ||
s.Equals("yes", StringComparison.OrdinalIgnoreCase);
// 使用转换器
string input = "Yes";
bool result = stringToBoolConverter(input);
Console.WriteLine(result); // 输出: True
示例2:使用Array.ConvertAll方法转换数组
string[] stringBools = { "true", "False", "1", "0", "yes", "no" };
// 使用Array.ConvertAll和自定义转换器
bool[] boolArray = Array.ConvertAll(stringBools, stringToBoolConverter);
foreach (bool b in boolArray)
{
Console.Write(b + " "); // 输出: True False True False True False
}
示例3:自定义转换器类
public class BoolConverter : IConverter<string, bool>
{
public bool Convert(string input)
{
return input switch
{
"true" or "1" or "yes" => true,
"false" or "0" or "no" => false,
_ => throw new ArgumentException("Invalid boolean string")
};
}
}
// 使用
var converter = new BoolConverter();
bool value = converter.Convert("yes"); // 返回true
其他常见转换场景
示例4:数字到布尔值转换
Converter<int, bool> intToBoolConverter = i => i != 0;
Console.WriteLine(intToBoolConverter(0)); // False
Console.WriteLine(intToBoolConverter(1)); // True
Console.WriteLine(intToBoolConverter(-5)); // True
示例5:对象到布尔值转换(处理可能为null的情况)
Converter<object, bool> objectToBoolConverter = o =>
o != null && (o.ToString().Equals("true", StringComparison.OrdinalIgnoreCase) ||
o.ToString() == "1");
Console.WriteLine(objectToBoolConverter(null)); // False
Console.WriteLine(objectToBoolConverter("TRUE")); // True
Console.WriteLine(objectToBoolConverter(1)); // True
示例6:使用内置的Boolean.Parse和Boolean.TryParse
// 直接使用内置方法
Converter<string, bool> builtInConverter = bool.Parse;
try
{
Console.WriteLine(builtInConverter("True")); // True
Console.WriteLine(builtInConverter("abc")); // 抛出FormatException
}
catch (FormatException)
{
Console.WriteLine("Invalid boolean format");
}
// 更安全的TryParse版本
string input = "abc";
if (bool.TryParse(input, out bool result))
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Conversion failed");
}
高级应用场景
示例7:在LINQ中使用转换器
List<string> stringList = new List<string> { "true", "false", "1", "0" };
// 使用ConvertAll方法
List<bool> boolList = stringList.ConvertAll(stringToBoolConverter);
// 或者使用LINQ Select
List<bool> boolList2 = stringList.Select(s => stringToBoolConverter(s)).ToList();
示例8:可配置的转换器
public class ConfigurableBoolConverter
{
private readonly string[] _trueValues;
private readonly string[] _falseValues;
public ConfigurableBoolConverter(string[] trueValues, string[] falseValues)
{
_trueValues = trueValues;
_falseValues = falseValues;
}
public bool Convert(string input)
{
if (_trueValues.Contains(input, StringComparer.OrdinalIgnoreCase))
return true;
if (_falseValues.Contains(input, StringComparer.OrdinalIgnoreCase))
return false;
throw new ArgumentException($"Cannot convert '{input}' to boolean");
}
}
// 使用
var converter = new ConfigurableBoolConverter(
trueValues: new[] { "on", "yes", "1" },
falseValues: new[] { "off", "no", "0" });
Console.WriteLine(converter.Convert("on")); // True
Console.WriteLine(converter.Convert("off")); // False
总结
C#中的Converter模式提供了灵活的类型转换机制,特别适用于:
-
需要将一种类型集合转换为另一种类型集合时
-
处理用户输入或外部数据源的不一致格式时
-
需要在不同系统或组件间转换数据格式时
-
需要可配置或可扩展的转换逻辑时
对于布尔型转换,Converter特别有用,因为布尔值在不同上下文中可能有多种表示形式(如"true"/"false"、"yes"/"no"、1/0等)。通过使用Converter,可以集中管理这些转换逻辑,提高代码的可维护性和一致性。