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")); // TrueConsole.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,可以集中管理這些轉換邏輯,提高代碼的可維護性和一致性。