[英]Read property in an anonymous object while creating the object. C#
Is there a way for me to read a property value I defined already in an anonymous object while creating the object?有没有办法让我在创建对象时读取我已经在匿名对象中定义的属性值?
here is an example这是一个例子
var a = new { PropA = "something", PropB = this.PropA + " and another thing"}
Perhaps defining it in a variable right before the declaration of a
would work?也许在声明
a
之前在变量中定义它会起作用?
var somethingValue = "something";
var a = new { PropA = somethingValue , PropB = somethingValue + " and another thing"}
Otherwise, I don't think you would be able to.否则,我认为您将无法做到。 You have yet to instantiate the object so
this.PropA
wouldn't work.您尚未实例化该对象,因此
this.PropA
不起作用。 To further elaborate, your question was " Is there a way for me to read a property value I defined already in an anonymous object while creating the object? " which doesn't entirely make sense, because you are creating the anonymous object, so the value isn't already defined in the object.更详细地说,您的问题是“我有没有办法在创建对象时读取我已经在匿名对象中定义的属性值? ”这并不完全有意义,因为您正在创建匿名对象,所以value 尚未在对象中定义。
Using dynamic binding can be helpful:使用动态绑定可能会有所帮助:
dynamic myObject = a;
myObject.PropB = ... //you can access any property that you know it exists
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.