C#中的Converter的具體應用
Converter是C#中一個非常有用的概念,主要用于類型轉(zhuǎn)換。它通常以委托或接口的形式出現(xiàn),允許開發(fā)者定義如何將一種類型轉(zhuǎn)換為另一種類型。下面我將詳細介紹Converter的概念、使用場景,并以布爾型轉(zhuǎn)換為例展示具體應用。
Converter的基本概念
1. Converter委托
在C#中,Converter<TInput, TOutput>
是一個泛型委托,定義在System
命名空間中。它的簽名如下:
public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
這個委托表示一個方法,該方法將對象從TInput
類型轉(zhuǎn)換為TOutput
類型。
2. 使用場景
Converter常用于:
- 集合類型轉(zhuǎn)換
- 數(shù)據(jù)格式化
- 類型適配
- 值轉(zhuǎn)換(如字符串到布爾值)
布爾型轉(zhuǎn)換示例
示例1:簡單的字符串到布爾值轉(zhuǎn)換
// 定義轉(zhuǎn)換器 Converter<string, bool> stringToBoolConverter = s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s.Equals("1", StringComparison.OrdinalIgnoreCase) || s.Equals("yes", StringComparison.OrdinalIgnoreCase); // 使用轉(zhuǎn)換器 string input = "Yes"; bool result = stringToBoolConverter(input); Console.WriteLine(result); // 輸出: True
示例2:使用Array.ConvertAll方法轉(zhuǎn)換數(shù)組
string[] stringBools = { "true", "False", "1", "0", "yes", "no" }; // 使用Array.ConvertAll和自定義轉(zhuǎn)換器 bool[] boolArray = Array.ConvertAll(stringBools, stringToBoolConverter); foreach (bool b in boolArray) { Console.Write(b + " "); // 輸出: True False True False True False }
示例3:自定義轉(zhuǎn)換器類
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
其他常見轉(zhuǎn)換場景
示例4:數(shù)字到布爾值轉(zhuǎn)換
Converter<int, bool> intToBoolConverter = i => i != 0; Console.WriteLine(intToBoolConverter(0)); // False Console.WriteLine(intToBoolConverter(1)); // True Console.WriteLine(intToBoolConverter(-5)); // True
示例5:對象到布爾值轉(zhuǎn)換(處理可能為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:使用內(nèi)置的Boolean.Parse和Boolean.TryParse
// 直接使用內(nèi)置方法 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中使用轉(zhuǎn)換器
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:可配置的轉(zhuǎn)換器
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
總結(jié)
C#中的Converter模式提供了靈活的類型轉(zhuǎn)換機制,特別適用于:
- 需要將一種類型集合轉(zhuǎn)換為另一種類型集合時
- 處理用戶輸入或外部數(shù)據(jù)源的不一致格式時
- 需要在不同系統(tǒng)或組件間轉(zhuǎn)換數(shù)據(jù)格式時
- 需要可配置或可擴展的轉(zhuǎn)換邏輯時
對于布爾型轉(zhuǎn)換,Converter特別有用,因為布爾值在不同上下文中可能有多種表示形式(如"true"/"false"、"yes"/"no"、1/0等)。通過使用Converter,可以集中管理這些轉(zhuǎn)換邏輯,提高代碼的可維護性和一致性。
到此這篇關于C#中的Converter的具體應用的文章就介紹到這了,更多相關C# Converter內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#實現(xiàn)將一個矩陣分解為對稱矩陣與反稱矩陣之和的方法
這篇文章主要介紹了C#實現(xiàn)將一個矩陣分解為對稱矩陣與反稱矩陣之和的方法,較為詳細的分析了矩陣分解運算的原理與C#實現(xiàn)技巧,需要的朋友可以參考下2015-08-08C#創(chuàng)建Windows服務與服務的安裝、卸載
這篇文章介紹了C#創(chuàng)建Windows服務與服務的安裝、卸載,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-02-02VS2019下安裝和破解?DevExpress?19.2?插件的詳細教程
這篇文章主要介紹了VS2019?安裝并破解?DevExpress?19.2?插件的詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03