你怎么能循环一个类的​​属性?

时间:2010-11-25 11:34:32

标签: c# reflection

c#中是否有一种方法可以遍历类的属性?

基本上我有一个包含大量属性的类(它基本上包含大型数据库查询的结果)。 我需要将这些结果作为CSV文件输出,因此需要将每个值附加到字符串中。

显然可以手动将每个值附加到字符串,但有没有办法有效地循环结果对象并依次为每个属性添加值?

11 个答案:

答案 0 :(得分:48)

不确定;你可以通过多种方式做到这一点;从反思开始(注意,这很慢 - 虽然适用于适量的数据):

var props = objectType.GetProperties();
foreach(object obj in data) {
    foreach(var prop in props) {
        object value = prop.GetValue(obj, null); // against prop.Name
    }
}

然而;对于更大量的数据,值得提高效率;例如,我在这里使用Expression API来预编译一个看起来写入每个属性的委托 - 这里的优点是不会对每行进行反映(对于大量数据,这应该明显更快) ):

static void Main()
{        
    var data = new[] {
       new { Foo = 123, Bar = "abc" },
       new { Foo = 456, Bar = "def" },
       new { Foo = 789, Bar = "ghi" },
    };
    string s = Write(data);        
}
static Expression StringBuilderAppend(Expression instance, Expression arg)
{
    var method = typeof(StringBuilder).GetMethod("Append", new Type[] { arg.Type });
    return Expression.Call(instance, method, arg);
}
static string Write<T>(IEnumerable<T> data)
{
    var props = typeof(T).GetProperties();
    var sb = Expression.Parameter(typeof(StringBuilder));
    var obj = Expression.Parameter(typeof(T));
    Expression body = sb;
    foreach(var prop in props) {            
        body = StringBuilderAppend(body, Expression.Property(obj, prop));
        body = StringBuilderAppend(body, Expression.Constant("="));
        body = StringBuilderAppend(body, Expression.Constant(prop.Name));
        body = StringBuilderAppend(body, Expression.Constant("; "));
    }
    body = Expression.Call(body, "AppendLine", Type.EmptyTypes);
    var lambda = Expression.Lambda<Func<StringBuilder, T, StringBuilder>>(body, sb, obj);
    var func = lambda.Compile();

    var result = new StringBuilder();
    foreach (T row in data)
    {
        func(result, row);
    }
    return result.ToString();
}

答案 1 :(得分:18)

foreach (PropertyInfo prop in typeof(MyType).GetProperties())
{
    Console.WriteLine(prop.Name);
}

答案 2 :(得分:5)

我在这个页面上尝试了各种推荐,但我无法让它们起作用。我从最顶层的答案开始(你会注意到我的变量同样被命名),并且我自己完成了它。这就是我的工作 - 希望它可以帮助别人。

var prop = emp.GetType().GetProperties();     //emp is my class
    foreach (var props in prop)
      {
        var variable = props.GetMethod;

        empHolder.Add(variable.Invoke(emp, null).ToString());  //empHolder = ArrayList
      }

***我应该提到这只会在你使用get; set; (公共)财产。

答案 3 :(得分:3)

您可以列出对象的属性

  IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();

然后使用foreach导航到列表中..

   foreach (var property in properties)
            {
              here's code...
            }

答案 4 :(得分:1)

使用类似

的内容
StringBuilder csv = String.Empty;
PropertyInfo[] ps this.GetType().GetProperties();
foreach (PropertyInfo p in ps)
{
    csv.Append(p.GetValue(this, null);
    csv.Append(",");
}

答案 5 :(得分:1)

var csv = string.Join(",",myObj
    .GetType()
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Select(p => p.GetValue(myObj, null).ToString())
    .ToArray());

答案 6 :(得分:0)

这是如何遍历vb.net中的属性,它在c#中的概念相同,只是翻译语法:

 Dim properties() As PropertyInfo = Me.GetType.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
            If properties IsNot Nothing AndAlso properties.Length > 0 Then
                properties = properties.Except(baseProperties)
                For Each p As PropertyInfo In properties
                    If p.Name <> "" Then
                        p.SetValue(Me, Date.Now, Nothing)  'user p.GetValue in your case
                    End If
                Next
            End If

答案 7 :(得分:0)

循环使用属性

Type t = typeof(MyClass);
foreach (var property in t.GetProperties())
{                
}

答案 8 :(得分:0)

string target = "RECEIPT_FOOTER_MESSAGE_LINE" + index + "Column";
PropertyInfo prop = xEdipV2Dataset.ReceiptDataInfo.GetType().GetProperty(target);
Type t = xEdipV2Dataset.ReceiptDataInfo.RECEIPT_FOOTER_MESSAGE_LINE10Column.GetType();
prop.SetValue(t, fline, null);

内容:目标对象必须是可以选择的

答案 9 :(得分:0)

string notes = "";

Type typModelCls = trans.GetType(); //trans is the object name
foreach (PropertyInfo prop in typModelCls.GetProperties())
{
    notes = notes + prop.Name + " : " + prop.GetValue(trans, null) + ",";
}
notes = notes.Substring(0, notes.Length - 1);

然后我们可以将notes字符串作为列写入日志表或文件。您必须使用System.Reflection来使用PropertyInfo

答案 10 :(得分:0)

从简单的类对象获取属性值....

class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var person1 = new Person
        {
            Name = "John",
            Surname = "Doe",
            Age = 47
        };

        var props = typeof(Person).GetProperties();
        int counter = 0;

        while (counter != props.Count())
        {
            Console.WriteLine(props.ElementAt(counter).GetValue(person1, null));
            counter++;
        }
    }
}