2013-05-03 97 views
1

所以,我有一个使用索引属性的类对象。我遍历对象的属性,但我想跳过索引属性本身。如何检查索引属性?

而不是检查属性名称是否为“Item”索引属性的默认值是否有另一种方法来检查此属性以跳过它?

这是我的代码:

具有index属性的类。

 public class MyClass{ 
    //Index Property 
    public object this[string propertyName] 
    { 
     get 
     { 
      return PropertyHelper.GetPropValue(this, propertyName); 
     } 
     set 
     { 
      if (PropertyHelper.GetPropType(this, propertyName) == typeof(Guid?)) 
      { 
       PropertyHelper.SetPropValue(this, propertyName, Guid.Parse(value.ToString())); 
      } 
      else if (PropertyHelper.GetPropType(this, propertyName) == typeof(int)) 
      { 
       PropertyHelper.SetPropValue(this, propertyName, int.Parse(value.ToString())); 

      } 
      else if (PropertyHelper.GetPropType(this, propertyName) == typeof(string)) 
      { 
       PropertyHelper.SetPropValue(this, propertyName,value.ToString()); 
      } 
     } 


    public Guid? Id { get; set; } 
    public int empId { get; set; } 
    public string morePropertiesLikeThis {get;set;} 

    } 

// PropertyHelper类

public static class PropertyHelper 
{ 
    public static object GetPropValue(object src, string propName) 
    { 
     return src.GetType().GetProperty(propName).GetValue(src, null); 
    } 

    public static Type GetPropType(object src, string propName) 
    { 
     return src.GetType().GetProperty(propName).PropertyType; 
    } 

    public static void SetPropValue(object src, string propName, object value) 
    { 
     src.GetType().GetProperty(propName).SetValue(src, value, null); 
    } 
} 

用法:

 //Build Query String 
     string parameters = "?"; 
     int r = 1; 
     foreach (PropertyInfo info in typeof (MyClass).GetProperties()) 
     { 
      //I want to use some less prone to change, than text Item 
      if (info.Name == "Item") 
      { 
       continue; 
      } 
      var property = PropertyHelper.GetPropValue(conditions, info.Name); 
      if (property != null) 
      { 
       if (r > 1) 
       { 
        parameters += "&" + info.Name + "=" + 
            conditions.GetType().GetProperty(info.Name).GetValue(conditions, null); 
       } 
       else 
       { 
        parameters += info.Name + "=" + 
           conditions.GetType().GetProperty(info.Name).GetValue(conditions, null); 
       } 
       r++; 
      } 

     } 

回答

2

只需使用PropertyInfo.GetIndexParameters - 如果返回的数组不为空,这是一个索引。

if (info.GetIndexParameters().Any()) 
{ 
    continue; 
} 
+0

非常感谢! – Rayshawn 2013-05-03 18:46:15