如何返回一個匿名類型,該類型取決於必須包含在匿名類型中的屬性所在的fields參數?任務實體擁有超過20個屬性,並且客戶希望接收不同的屬性組合。如何返回自定義匿名類型?
public class Test
{
public class Task
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
//... more 20 properties
}
public List<Task> Tasks = new List<Task>();
public Test()
{
Tasks.Add(new Task { Id = 1, Name = "Task #1", Description = "Description task #1" });
Tasks.Add(new Task { Id = 2, Name = "Task #2", Description = "Description task #2" });
Tasks.Add(new Task { Id = 3, Name = "Task #3", Description = "Description task #3" });
}
public IEnumerable<object> GetAllTasks(string fields)
{
//if fields == 'Id,Name' then return anonymous type new { Id = t.Id, Name = t.Name }
return Tasks.Select(t => new { Id = t.Id, Name = t.Name });
//if fields == 'Id,Name,Description' then return anonymous type new { Id = t.Id, name = t.Name, Description = t.Description }
return Tasks.Select(t => new { Id = t.Id, Name = t.Name, Description = t.Description });
}
}
匿名類型是在編譯類型是已知的。你想在運行時動態構建類型。這是完全不同的。這也意味着'GetAllTasks'的消費者必須能夠處理動態類型。除此之外,不建議返回匿名類型。 – 2013-02-19 08:52:17
您已經定義了類Task,爲什麼不使用它而不是匿名類型? – 2013-02-19 08:52:52
您可以使用反射嘗試設置任務對象中傳遞的所有字段的值 – glosrob 2013-02-19 08:53:08