[英]A generic function in C# that take a List of random class and an array of certain property names as parameters
我想编写一个可以打印任何特定属性值的通用函数。 一个参数是随机类的列表,另一个参数是某些类属性名称的数组。 该函数能够打印列表中每个元素的给定属性值。 假设我有两个类别的两个列表:
class visitor {
public string name;
public string age;
public string address;
public string nationality;
}
class menu {
public string dish;
public double prise;
public string chef;
public bool isForVIP;
}
List<visitor> visitorList, List<menu> menuList
现在我只想要函数void GenericOutput(List<AnyObject> objList,string[] certainProperties)
输出每个类属性的一部分。 例如:
GenericOutput(visitorList,new string[]{ "name","age" });
GenericOutput(menuList,new string[]{ "dish","double","isForVIP" });
如何在 C# 中设计函数? 有人能帮我吗?
通过使用反射,您可以:
例子:
public void GenericOutput<T>(List<T> objects, string[] propertyNames)
{
// Get the generic type.
Type type = typeof(T);
// Get the requested properties of the type.
var propertyInfos = propertyNames.Select(pn => type.GetProperty(pn));
foreach (var obj in objects)
{
foreach (var propertyInfo in propertyInfos)
{
// For each given object, iterate the properties of
// the type and get the property value from the object.
var value = propertyInfo.GetValue(obj);
// Print or do whatever with the value...
Console.WriteLine(value);
}
}
}
试试这个,
class Program
{
static void Main(string[] args)
{
var visitors = new List<Visitor>()
{
new Visitor(){Name="Visitor1",Age="30",Address="adress1",Nationality="Nationality1"},
new Visitor(){Name="Visitor2",Age="20",Address="adress2",Nationality="Nationality2"},
new Visitor(){Name="Visitor3",Age="10",Address="adress3",Nationality="Nationality3"},
new Visitor(){Name="Visitor4",Age="50",Address="adress4",Nationality="Nationality4"},
new Visitor(){Name="Visitor5",Age="90",Address="adress5",Nationality="Nationality5"},
};
GenericOutput(visitors, new string[] { "Name", "Age", "Address" });
Console.ReadKey();
}
private static void GenericOutput<T>(List<T> obj, string[] properties)
{
var t = typeof(T);
foreach (var item in obj)
{
foreach (var propName in properties)
{
var propValue = (t.GetProperty(propName).GetValue(item) ?? string.Empty).ToString();
Console.WriteLine($"{propName}:{propValue}");
}
Console.WriteLine("-----------");
}
}
}
class Visitor
{
public string Name { get; set; }
public string Age { get; set; }
public string Address { get; set; }
public string Nationality { get; set; }
}
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.