如何在c#中循环遍历对象的属性

本文关键字:遍历 对象 属性 循环 | 更新日期: 2023-09-27 18:10:56

我有一个方法,它可以获取对象的属性值,并在其上添加一些逗号。我想使这个generainc可以与其他对象一起使用。

            foreach (var row in rows.ToList())
            {
                sbResult.Append(
                    delimiter + row.MediaName + delimiter + separator +
                    delimiter + row.CountryName + delimiter + separator +
                    delimiter + row.ItemOverRideDate + delimiter + separator +
                    delimiter + row.Rating + delimiter + separator +
                    delimiter + row.BatchNo + delimiter + separator +
                    delimiter + row.NoInBatch + delimiter + separator +
                    delimiter + row.BatchDate + delimiter + separator +
                    delimiter + row.DataType + delimiter + separator +
                    delimiter + row.ByLine + delimiter + separator +
                    delimiter + row.IssueNo + delimiter + separator +
                    delimiter + row.Issue + delimiter + separator +
                    delimiter + row.MessageNo + delimiter + separator +
                    delimiter + row.Message + delimiter + separator +
                    delimiter + row.SourceName + delimiter + separator +
                    delimiter + row.SourceType + delimiter + separator);
                //end of each row
                sbResult.AppendLine();
            }

我尝试过使用var rowData = row.GetType().GetProperties();,但它只返回属性本身,我不知道如何获取属性的值。

如何在c#中循环遍历对象的属性

由于Type.GetProperties返回一个PropertyInfo的集合,因此您可以调用PropertyInfo.GetValue。以下是如何使用LINQ:做到这一点(以及其他所有功能(

var line = string.Join(
             row.GetType().GetProperties()
              .Select(pi => pi.GetValue(row))
              .Select(v => delimiter + v.ToString() + delimiter),
             separator);

但是,您可能需要重新考虑您的方法。如果GetProperties获取静态属性或索引器以及"正常"属性,则此代码将中断;它还要求代码在完全信任的情况下运行(否则就不可能进行反射(。最后,它将是,因为a(反射本质上是慢的,b(它将一次又一次地反思相同的事情,而不缓存它已经发现的任何信息。

除了上述潜在问题之外,如果您以后想要过滤打印出来的内容的可能性很小,那么最好将此逻辑封装在row上的(virtual?(方法中,然后执行类似的操作

sbResult.AppendLine(row.SerializeAsLine());

您可以使用类似的东西来迭代特定类型的所有属性:

public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
{
    return from p in obj.GetType().GetProperties()
            where p.PropertyType == typeof(T)
            select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
}

然后,您可以将所有字符串属性的类型指定为string

可配制样品:

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
    class Program
    {
        private static void Main()
        {
            var test = new Test
            {
                Str1 = "S1",
                Str2 = "S2",
                Str3 = "S3",
                Str4 = "S4"
            };
            foreach (var property in PropertiesOfType<string>(test))
            {
                Console.WriteLine(property.Key + ": " + property.Value);
            }
        }
        public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
        {
            return from p in obj.GetType().GetProperties()
                    where p.PropertyType == typeof(T)
                    select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
        }
    }
    public class Test
    {
        public string Str1 { get; set; }
        public string Str2 { get; set; }
        public string Str3 { get; set; }
        public string Str4 { get; set; }
    }
}

在这里。

List<PropertyInfo> _propInfo = _row.GetType().GetProperties();
    foreach (var item in _propInfo)
    {
    object _value = item.GetValue(_row, null);
    if (_value != null)
    {
    // Save the Value
    }
    }

GetProperties返回一个PropertyInfo数组,因此使用GetValue方法并使用对象作为输入来获取每个属性的值。这是代码:

public class MyClass
{
    public string MyProperty1 { get; set; }
    public string MyProperty2 { get; set; }
    public string MyProperty3 { get; set; }
}

然后

MyClass myObj = new MyClass() { MyProperty1 = "first", MyProperty2 = "second", MyProperty3 = "third" };
List<string> array = new List<string>();
foreach (var item in typeof(MyClass).GetProperties())
{
    array.Add(item.GetValue(myObj, null).ToString());
}
var result = string.Join(",", array); //use your own delimiter 
var values = instance
    .GetType()
    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
    .Select(z => string.Format("{0}: {1}'n", z.Name, z.GetValue(instance, null)));
string res = string.Concat(values);

其中instance是对象的实例。如果需要StringBuilder(取决于属性的数量(,您可能希望避免使用LINQ并使用循环。