[英]Access anonymous object property from static class c#
I have a static class with multiple anonymous objects. 我有一个带有多个匿名对象的静态类。 Each object, has a different amount of properties, but each property is always a object of created class. 每个对象具有不同数量的属性,但每个属性始终是已创建类的对象。
static public class Fields{
static public Object FieldInfo1 = new {
Customer = new FieldInformation("value1","value2")
}
static public Object FieldInfo2 = new {
Customer = new FieldInformation("value1","value2"),
Company = new FieldInformation("value1","value2"),
}
}
I try to access Fields.FieldInfo1.Customer
in second class (Program.cs, its a console application) but it isn't working, I only get Fields.FieldInfo1.
我尝试在第二个类(Program.cs,它是一个控制台应用程序)中访问Fields.FieldInfo1.Customer
但它不起作用,我只获得Fields.FieldInfo1.
What am I doing wrong? 我究竟做错了什么?
You need to cast it to the type of the object. 您需要将其强制转换为对象的类型。 Because you have non (at compile time) cast as dynamic
: 因为你有非(在编译时)强制转换as dynamic
:
var obj = Fields.FieldInfo1 as dynamic;
var value = obj.Customer.Prop1; // "value1"
But I don't see why you need to do it this way. 但我不明白为什么你需要这样做。 This is not C# like, which is a strongly typed language. 这不是C#like,这是一种强类型语言。 In my opinion you should rethink your design. 在我看来,你应该重新考虑你的设计。
This might give you a starting point for when it is right to use anonymous types 这可能会为您提供何时使用匿名类型的起点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.