首页 > 解决方案 > 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# 中设计函数?有人能帮帮我吗?

标签: c#.net

解决方案


通过使用反射,您可以:

  1. 创建一个泛型方法。
  2. 从泛型类型参数获取运行时类型。
  3. 获取有关类型属性的信息。
  4. 从该类型的每个对象中提取值。

例子:

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);
        }
    }
}

推荐阅读