简体   繁体   English

C# 中的通用函数,它采用随机类列表和某些属性名称的数组作为参数

[英]A generic function in C# that take a List of random class and an array of certain property names as parameters

I want to write a generic function that can print any certain property values.我想编写一个可以打印任何特定属性值的通用函数。 One parameter is a list of random class, another parameter is an array of certain class property names.一个参数是随机类的列表,另一个参数是某些类属性名称的数组。 The function is able to print given property value of each element in the list.该函数能够打印列表中每个元素的给定属性值。 Assuming I have two classes of two lists of them:假设我有两个类别的两个列表:

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

Now I want only the function void GenericOutput(List<AnyObject> objList,string[] certainProperties) to output a part of each class properties.现在我只想要函数void GenericOutput(List<AnyObject> objList,string[] certainProperties)输出每个类属性的一部分。 For example:例如:

GenericOutput(visitorList,new string[]{ "name","age" });
GenericOutput(menuList,new string[]{ "dish","double","isForVIP" });

How can I design the function in C#?如何在 C# 中设计函数? Could some help me?有人能帮我吗?

By using reflection, you can:通过使用反射,您可以:

  1. Create a generic method.创建一个泛型方法。
  2. Get the run time type from the generic type argument.从泛型类型参数获取运行时类型。
  3. Get information about the properties of the type.获取有关类型属性的信息。
  4. Extract the values from each object of the type.从该类型的每个对象中提取值。

Example:例子:

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

Try this,试试这个,

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

Result:结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM