通过泛型方式获取不同集合属性的拼接字符串
今天写代码时遇到了一个问题,假如有两个不同类型的集合,如何通过一个方法拼接集合中的某个属性成为一个字符串
尝试了一种泛型的写法,记录一下
/// <summary>
/// 主方法
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
List<Animals> listA = new List<Animals>
{
new Animals { AnimalsName = "Dog", Sex = "Male" },
new Animals { AnimalsName = "Cat", Sex = "Female" },
new Animals { AnimalsName = "Monkey", Sex = "Male" }
};
List<Plant> listB = new List<Plant>
{
new Plant { PlantName = "Rose", PlantColour = "Red" },
new Plant { PlantName = "Grass", PlantColour = "Green" },
new Plant { PlantName = "Sunflower", PlantColour = "Yellow" }
};
Console.WriteLine(GetStr(listA)); //输出 Dog,Cat,Monkey
Console.WriteLine(GetStr(listB)); //输出 Rose,Grass,Sunflower
Console.ReadKey();
}
/// <summary>
/// 获取拼接字符串
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="list">传入集合</param>
/// <returns></returns>
public static string GetStr<T>(List<T> list) where T : class
{
string str = string.Empty;
//集合为空时,直接返回
if (list.Count == 0)
return "";
//获取实体集合类型
Type objType = typeof(T);
string field = string.Empty;
//根据不同实体类型选择不同的属性名称
switch (objType.Name)
{
case nameof(Animals):
field = "AnimalsName";
break;
case nameof(Plant):
field = "PlantName";
break;
}
//获取对应参数名的参数信息
PropertyInfo proInfo = objType.GetProperty(field);
//循环拼接字符串
foreach (var item in list)
{
str += proInfo?.GetValue(item) + ",";
}
//去除最后一位 ','
return str.Remove(str.Length - 1);
}
/// <summary>
/// 动物类
/// </summary>
public class Animals
{
public string AnimalsName { get; set; }
public string Sex { get; set; }
}
/// <summary>
/// 植物类
/// </summary>
public class Plant
{
public string PlantName { get; set; }
public string PlantColour { get; set; }
}
还有很多写法不足的地方,欢迎各位大佬来指正,或者还有其他更好的方法也可以来讨论一下