开发者

iterate all properties in the list

I have List (Of Report). Report has 90 properties. I dont want write them each and every propertiy to get values for properties. Is there any waht to get propeties values from the List

Ex:

Dim mReports开发者_C百科 as new List(Of Reports)
mReport = GetReports()

For each mReport as Report In mReports
   'Here I want get all properties values without writing property names
next


You can use reflection:

static readonly PropertyInfo[] properties = typeof(Reports).GetProperties();

foreach(var property in properties) {
    property.GetValue(someInstance);
}

However, it will be slow.

In general, a class with 90 proeprties is poor design.
Consider using a Dictionary or rethinking your design.


PropertyInfo[] props = 
     obj.GetType().GetProperties(BindingFlags.Public |BindingFlags.Static);
foreach (PropertyInfo p in props)
{
  Console.WriteLine(p.Name);
}


Sounds like a good fit for reflection or meta-programming (depending on the performance required).

var props=typeof(Report).GetProperties();
foreach(var row in list)
foreach(var prop in props)
    Console.WriteLine("{0}={1}",
        prop.Name,
        prop.GetValue(row));


I don't speak VB.NET fluently, but you can easily translate something like this to VB.NET.

var properties = typeof(Report).GetProperties();
foreach(var mReport in mReports) {
    foreach(var property in properties) {
       object value = property.GetValue(mReport, null);
       Console.WriteLine(value.ToString());
    }
}

This is called reflection. You can read about its uses in .NET on MSDN. I used Type.GetProperties to get the list of properties, and PropertyInfo.GetValue to read the values. You might need to add various BindingFlags or check properties like PropertyInfo.CanRead to get exactly the properties that you want. Additionally, if you have any indexed properties, you will have to adjust the second parameter to GetValue accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜