字符串插值:如何让该函数支持任意类型?
解决方法:使用泛型让函数支持任意类型
要让你的ForEach函数支持任意类型的列表,核心是用泛型替代固定的dynamic类型,这样外层逻辑不需要关心列表元素的具体类型,只需要把元素传递给传入的处理函数即可。
修改思路
原来的函数把列表类型硬编码成了List<dynamic>,我们只需要引入泛型参数<T>,让函数能接受任意类型的List<T>,同时把内部的处理函数也改成对应类型的Func<T, string>,就能完美适配各种类型的列表了。
修改后的完整代码
using System; using System.Collections.Generic; using System.Text; class Program { // 改成泛型方法,支持任意类型的列表 static string ForEach<T>(List<T> list, Func<T, string> func, string separator) { var bldr = new StringBuilder(); var first = true; foreach (var obj in list) { if (!first) bldr.Append(separator); first = false; bldr.Append(func(obj)); } return bldr.ToString(); } static void Main(string[] args) { var tableName = "customers"; var cols = new List<dynamic> { new { Name = "surname"}, new { Name = "firstname"}, new { Name = "dateOfBirth"} }; // 编译器会自动推断泛型参数T的类型 var InsertStatement = $"Insert into { tableName } ( {ForEach(cols, col => col.Name, ", ")} )"; Console.WriteLine(InsertStatement); Console.ReadLine(); } }
运行结果
Insert into customers ( surname, firstname, dateOfBirth )
通用性验证
现在这个ForEach函数可以处理任意类型的列表,比如:
- 处理字符串列表:
var stringList = new List<string> { "apple", "banana", "cherry" }; var strResult = ForEach(stringList, s => $"'{s}'", ", "); // 输出:'apple', 'banana', 'cherry' - 处理自定义类列表:
public class Product { public int Id { get; set; } public string Name { get; set; } } var products = new List<Product> { new Product { Id=1, Name="Laptop" }, new Product { Id=2, Name="Phone" } }; var prodResult = ForEach(products, p => $"({p.Id}, '{p.Name}')", ", "); // 输出:(1, 'Laptop'), (2, 'Phone')
这样修改后,你的函数就完全摆脱了dynamic的限制,能灵活处理任何类型的列表,同时保留了原有的功能逻辑。
内容的提问来源于stack exchange,提问作者bbsimonbb
相关产品推荐
相关产品推荐

