2017-02-24 184 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類的當前實例傳遞的參數,這是我敢肯定不是你想要的。

在你的示例代碼。