2017-02-24 86 views
2

我有这样的代码反射物体的属性

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

'但是我在line'越来越例外请张贴例外。 – Stefan

+0

NullReferenceException? –

+0

{“对象与目标类型不匹配。”} – dan

回答

3

您应该this改变负载特性(即不具有这样的性质),以参数对象:

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

work中, 谢谢!! ! – dan

2

您传递错误的引用作为参数传递给方法,你需要通过你用得到的种类和属性的对象,所以改变:

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

到:

p.GetValue(obj) 

你的陈述p.GetValue(this) currenly意味着Test类的当前实例传递的参数,这是我敢肯定不是你想要的。

在你的示例代码。