2017-04-13 25 views
2

我試圖做一個函數,允許我將一個類映射到另一個類。它幾乎工作,除了我的Id屬性沒有被映射,我不明白爲什麼。PropertyInfo SetValue沒有設置我的對象的ID

在底部有一個到在線編碼示例的鏈接,按F8運行它。 在輸出,你可以看到下面的代碼是如何顯示我的Id:

if(propertyInfo.Name == "Id") 
    Console.WriteLine(propertyInfo.GetValue(currentEUser)); 

但是當我嘗試users.ForEach(u => Console.WriteLine(String.Format("{0}, {1}, {2}", u.Id, u.Name, u.Age)));,沒有標識的使用。爲什麼?

public class eUser 
{ 
    public int Id {get;set;} 
    public String Name {get;set;} 
    public int Age {get { return 10;}} 

    public eUser(int id, String name){ 
     Id = id; 
     Name = name; 
    } 
} 

public class User 
{ 
    public int Id {get;set;} 
    public String Name {get;set;} 
    public int Age {get { return 10;}} 
} 

我有我的主要程序,應該從EUSER我所有的字段映射到用戶對象

public class Program 
{ 

    public static void Main(string[] args) 
    { 
     // init 
     List<User> users = new List<User>(); 
     User user = new User(); 

     List<eUser> eUsers = new List<eUser>(); 
     eUsers.Add(new eUser(1, "Joris")); 
     eUsers.Add(new eUser(2, "Thierry")); 
     eUsers.Add(new eUser(3, "Bert")); 



     IList<PropertyInfo> eUserProps = new List<PropertyInfo>(eUsers.FirstOrDefault().GetType().GetProperties()); 
     foreach(eUser currentEUser in eUsers){ 

      foreach (PropertyInfo propertyInfo in eUserProps) 
      { 
       // Test to only map properties with a Set field 
       if (propertyInfo.CanWrite) 
       { 
        // Test to see if Id comes through 
        if(propertyInfo.Name == "Id") 
         Console.WriteLine(propertyInfo.GetValue(currentEUser)); 

        // Create new user 
        user = new User(); 

        //Map eUser to User object 
        typeof(User) 
         .GetProperty(propertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField) 
         .SetValue(user, propertyInfo.GetValue(currentEUser)); 
       } 

      } 
      users.Add(user); 

     } 

     users.ForEach(u => Console.WriteLine(String.Format("{0}, {1}, {2}", u.Id, u.Name, u.Age))); 
    } 
} 

代碼示例:http://rextester.com/SHNY15243

+1

您正在爲每個「eUser」對象的每個*屬性*創建* new *'User'對象。創建的第二個'User'對象沒有'Id'集合,所以'Id'的值默認爲'0'。 –

回答

3

移動user = new User();到第二foreach循環之外。

+0

這樣做,謝謝!然而,不知道爲什麼雖然.. –

+0

沒關係,現在有道理! –

相關問題