2009-11-04 35 views

回答

2

下将选择所有属性/值到一个包含名称/值对你有兴趣的属性匿名类型的IEnumerable的,它使假设性质是公开的,你正在从该对象的方法访问。如果属性未公开,则需要使用BindingFlags来指示您需要非公共属性。如果来自对象之外,则将this替换为感兴趣的对象。

var properties = this.GetType() 
        .GetProperties() 
        .Where(p => p.Name.StartsWith("Value")) 
        .Select(p => new { 
          Name = p.Name, 
          Value = p.GetValue(this, null) 
         });  
7

使用反射。

public static string PrintObjectProperties(this object obj) 
{ 
    try 
    { 
     System.Text.StringBuilder sb = new StringBuilder(); 

     Type t = obj.GetType(); 

     System.Reflection.PropertyInfo[] properties = t.GetProperties(); 

     sb.AppendFormat("Type: '{0}'", t.Name); 

     foreach (var item in properties) 
     { 
      object objValue = item.GetValue(obj, null); 

      sb.AppendFormat("|{0}: '{1}'", item.Name, (objValue == null ? "NULL" : objValue)); 
     } 

     return sb.ToString(); 
    } 
    catch 
    { 
     return obj.ToString(); 
    } 
} 
1

您可以使用Reflection来完成此操作,获取该类的PropertyInfo对象并检查它们的名称。

3

您可以考虑使用集合或自定义索引器。

public object this[int index] 
{ 
    get 
    { 
     ... 
    } 

    set 
    { 
     ... 
    } 
} 

然后你可以说;

var q = new YourClass(); 
q[1] = ... 
q[2] = ... 
... 
q[30] = ... 
+0

为什么downvote?他的问题表明“Value1”到“Value30”这是自定义索引者所做的。 – 2009-11-04 17:08:52