我正在尝试为MVC控制器进行数据绑定, 因此我需要一个通用类来改变我的类:
public class Subsystem
{
public int Id { get; set; }
public string Name { get; set; }
}
我需要一个通用的方法来解决这个问题:
public Subsystem[] GetSubsystems()
{
return new Subsystem[]
{
new Subsystem() {Id=1, Name = "A"},
new Subsystem() {Id=2, Name = "B"},
new Subsystem() {Id=3, Name = "C"}
};
}
进入这个:
public object[] GetSubsystems()
{
return new object[]
{
new object[] {Id=1, Name = "A"},
new object[] {Id=2, Name = "B"},
new object[] {Id=3, Name = "C"}
};
}
答案 0 :(得分:1)
我仍然认为这可能不是你真正追求的最佳解决方案,但你可以使用Linq将其转换为匿名对象数组:
public static object[] GetSubsystems()
{
Subsystem[] subsystems = new Subsystem[]
{
new Subsystem() {Id=1, Name = "A"},
new Subsystem() {Id=2, Name = "B"},
new Subsystem() {Id=3, Name = "C"}
};
object[] anonymousSubsystems = (from subsystem in subsystems
select (object)(new { Id = subsystem.Id, Name = subsystem.Name })).ToArray();
return anonymousSubsystems;
}
你的“this”中的内容实际上是不可能的,你给出的Linq查询的结果将等同于:
public object[] GetSubsystems()
{
return new object[]
{
new {Id=1, Name = "A"},
new {Id=2, Name = "B"},
new {Id=3, Name = "C"}
};
}