我在C#中有如下对象列表:
var items = new List<object> {
new { id = 1, parentId = 0, children = new List<object>() },
new { id = 2, parentId = 3, children = new List<object>() },
new { id = 3, parentId = 1, children = new List<object>() },
new { id = 4, parentId = 0, children = new List<object>() }
};
例如,我想访问列表中第一个对象的id
属性,但是当我执行以下操作时:
items[0].id
我收到以下错误:
“对象”不包含“ id”的定义,并且不可访问 扩展方法'id'接受类型为'object'的第一个参数 可以找到(您是否缺少using指令或程序集 参考?)
如何访问上述C#对象列表中的四个对象文字的属性?
谢谢。
答案 0 :(得分:3)
我认为这是一种更c#的处理方式。
class A
{
public int Id { get; set; }
public int ParentId { get; set; }
public List<A> Children { get; } = new List<A>();
}
class Program
{
static void Main(string[] args)
{
var items = new List<A> {
new A { Id = 1, ParentId = 0},
new A { Id = 2, ParentId = 3},
new A { Id = 3, ParentId = 1},
new A { Id = 4, ParentId = 0}
};
}
}
答案 1 :(得分:2)
您可以使用动态,因为您尤其不了解类型
var items = new List<object> {
new { id = 1, parentId = 0, children = new List<object>() },
new { id = 2, parentId = 3, children = new List<object>() },
new { id = 3, parentId = 1, children = new List<object>() },
new { id = 4, parentId = 0, children = new List<object>() }
};
dynamic dy = items[0];
Console.WriteLine(dy.id);
答案 2 :(得分:1)
使用所需的属性定义类型:
public class Foo {
public Foo(){
Children = new List<Foo>();
}
public int Id {get;set;}
public int? ParentId {get;set;}
public List<Foo> Children {get;set;}
}
}
然后:
var items = new List<Foo> {
new { id = 1, ParentId = 0 },
new { id = 2, ParentId = 3},
new { id = 3, ParentId = 1},
new { id = 4, ParentId = 0}
};
答案 3 :(得分:1)
要访问object
的成员,您需要将其强制转换为定义该成员的类型。这有点棘手,因为类型是匿名的,但并非不可能:
var items = new List<object> {
new { id = 1, parentId = 0, children = new List<object>() },
new { id = 2, parentId = 3, children = new List<object>() },
new { id = 3, parentId = 1, children = new List<object>() },
new { id = 4, parentId = 0, children = new List<object>() }
};
T Cast<T>(T ignore, object obj) => (T)obj;
var typedNull = true ? null : new { id = default(int), parentId = default(int), children = default(List<object>) };
var typedObject = Cast(typedNull, items[2]);
Console.WriteLine(typedObject.id);
Console.WriteLine(typedObject.parentId);
但是您最好为此声明一个自己的命名类型。