设置嵌套类的值

时间:2015-01-27 00:24:34

标签: c# reflection

我有两个班级:

public class Task {
    public int TaskId {get; set;}
    public string Desc {get; set;}
    public Client taskClient {get; set;}
}

public class Client {
    public string Firstname {get;set;}
    public string Lastname {get;set;}
    ...(other 18 properties)
}

我有值列表(大约100),结构如下:

TaskId = 1, Desc = "Task 1", Firstname = "Mark", Lastname ="Smith". 

在这种情况下,如何使用反射创建新任务?

1 个答案:

答案 0 :(得分:0)

使用Activator Class创建一个对象,并通过反射填充值。

var clientType = typeof(Client);
var c = Activator.CreateInstance(clientType);
clientType.GetProperty("Firstname").SetValue(c, "Mark");
clientType.GetProperty("Lastname").SetValue(c, "Smith");

var taskType = typeof(Task);
var t = Activator.CreateInstance(taskType);
taskType.GetProperty("TaskId").SetValue(t, 1);
taskType.GetProperty("Desc").SetValue(t, "Task 1");
taskType.GetProperty("taskClient").SetValue(t, c);