c# - C# 中的泛型函数,它采用随机类列表和某些属性名称的数组作为参数
问题描述
我想编写一个可以打印任何特定属性值的通用函数。一个参数是随机类列表,另一个参数是某些类属性名称的数组。该函数能够打印列表中每个元素的给定属性值。假设我有两个类别的两个列表:
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);
}
}
}
推荐阅读
- karate - 空手道 DSL:如何检查 JSON 对象是否是可选的,但如果该对象来自该对象内的键应该是正确的模式?
- react-native - 如何在react-native中查找元素是否存在于数组中
- ruby-on-rails - Pagy gem:UI 小部件的放置打破了分页
- c# - 如何在 C# 中设置 Excel 工作簿的可见性
- python - For 循环似乎比应有的变量添加了更多内容
- php - 将 PHP 5.6 升级到 7.2
- php - 从数组中添加唯一的随机值
- javascript - 解码字符串,以便我可以解析 JSON
- automation - 如何等待全名在量角器的文本框中输入
- ms-access - 从子窗体中的表中获取 CurrentRecord