繁体   English   中英

反映对象属性

[英]Reflection of object properties

我有这个代码

 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() 

你应该改变加载性能this (不具有这样的性质),以参数对象:

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

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

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

至:

p.GetValue(obj)

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

在您的示例代码中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM