对象属性的反映

时间:2017-02-24 09:52:33

标签: c# .net reflection

我有这个代码

 public class ParameterOrderInFunction : Attribute
    {
        public int ParameterOrder { get; set; }
        public ParameterOrderInFunction(int parameterOrder)
        {
            this.ParameterOrder = parameterOrder;
        }
    }


    public interface IGetKeyParameters
    {

    }

    public class Person: IGetKeyParameters
    {

        [ParameterOrderInFunction(4)]
        public string Age { get; set; }
        public string Name { get; set; }
        [ParameterOrderInFunction(3)]
        public string Address { get; set; }
        [ParameterOrderInFunction(2)]
        public string Language { get; set; }

        [ParameterOrderInFunction(1)]
        public string City { get; set; }

        public string Country { get; set; }        
    }


    class Program
    {
        static void Main(string[] args)
        {

            Person person = new Person();

            person.Address = "my address";
            person.Age = "32";
            person.City = "my city";
            person.Country = "my country";            

            Test t = new Test();
            string result = t.GetParameter(person);
            //string result = person.GetParameter();

            Console.ReadKey();

        }      
    }

    public class Test
    {
        public string GetParameter(IGetKeyParameters obj)
        {
            string[] objectProperties = obj.GetType()
               .GetProperties()
               .Where(p => Attribute.IsDefined(p, typeof(ParameterOrderInFunction)))
                 .Select(p => new
                 {
                     Attribute = (ParameterOrderInFunction)Attribute.GetCustomAttribute(p, typeof(ParameterOrderInFunction), true),
                     PropertyValue = p.GetValue(this) == null ? string.Empty : p.GetValue(this).ToString()
                 })
               .OrderBy(p => p.Attribute.ParameterOrder)
               .Select(p => p.PropertyValue)
               .ToArray();
            string keyParameters = string.Join(string.Empty, objectProperties);
            return keyParameters;

        }
    }

我想要做的是将属性值作为一个字符串获得一些顺序。

如果我将函数GetParameter放在Person类中,它可以正常工作。 但是,我想将GetParameter函数与其他类一起使用, 所以我创建空接口。 现在我希望IGetKeyParameters类型的每个对象都可以使用该函数。 但我在这行中得到例外:

PropertyValue = p.GetValue(this) == null ? string.Empty : p.GetValue(this).ToString() 

2 个答案:

答案 0 :(得分:3)

您应该将this(没有此类属性)的加载属性更改为参数对象:

PropertyValue = p.GetValue(obj) == null ? string.Empty : p.GetValue(obj).ToString()

答案 1 :(得分:2)

您将错误的引用作为参数传递给方法,您需要传递用于获取类型和属性的对象,因此更改:

p.GetValue(this)  // this means pass current instance of containing class i.e. Test

为:

p.GetValue(obj)

您的语句p.GetValue(this)当前意味着将类Test的当前实例作为参数传递,我很确定不是您想要的。

在您的示例代码中。