我正在尝试创建一个函数,允许我将一个类映射到另一个类。它几乎可以工作,只是我的 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) )));
,没有可用的 ID。为什么?
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 映射到 User 对象
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)));
}
}
最佳答案
将 user = new User();
移至第二个 foreach
循环之外。
关于c# - PropertyInfo SetValue 未设置我的对象的 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43388220/