2017-04-13 44 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

没关系,现在有道理! –

相关问题