c# - PropertyInfo SetValue 未设置我的对象的 Id

标签 c# propertyinfo

我正在尝试创建一个函数,允许我将一个类映射到另一个类。它几乎可以工作,只是我的 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)));
    }
}

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

最佳答案

user = new User(); 移至第二个 foreach 循环之外。

关于c# - PropertyInfo SetValue 未设置我的对象的 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43388220/

相关文章:

c# - 为什么我的保存使用我的文本框的初始值而不是输入的值?

c# - 从 Azure Blob 存储反序列化对象的最快方法?

c# - Asp.net动态数据修改列大小

c# - someString.IndexOf(someString) 在 .NET 4 下返回 1 而不是 0

c# - 如何使用 C# 反射将值设置为嵌套属性。?

c# - 反射 - 获取嵌套对象的属性

c# - 非静态方法需要 PropertyInfo.SetValue 中的目标

c# - DataGridAutoGeneratingColumnEventArgs.PropertyDescriptor 是什么类型的?

.net - BindingFlags 枚举中的 GetField、SetField、GetProperty 和 SetProperty 是什么?

c# - 如何将位图另存为图标?