簡體   English   中英

如何檢查索引屬性?

[英]How to check for indexed property?

所以,我有一個使用index屬性的類對象。 我遍歷對象的屬性,但是我想跳過index屬性本身。

不是檢查屬性名稱是否為“ 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++;
            }

        }

只需使用PropertyInfo.GetIndexParameters如果返回的數組不為空,則為索引器。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM