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++;
            }

        }
4

1 に答える 1

2

使用するだけPropertyInfo.GetIndexParametersです-返された配列が空でない場合、それはインデクサーです。

if (info.GetIndexParameters().Any())
{
    continue;
}
于 2013-05-03T18:37:18.863 に答える