访问 C# 对象初始值设定项内的属性读取值
我想在对象初始值设定项中引用对象的属性。问题是该变量尚不存在,因此我无法像正常(object.method)一样引用它。不知道在对象初始化的时候是否有一个关键字来引用create中的对象。
当我编译以下代码时,出现错误 - '名称'宽度'在上下文中不存在。我明白为什么会出现此错误,但我的问题是:是否有任何语法可以执行此操作?
public class Square
{
public float Width { get; set; }
public float Height { get; set; }
public float Area { get { return Width * Height; } }
public Vector2 Pos { get; set; }
public Square() { }
public Square(int width, int height) { Width = width; Height = height; }
}
Square mySquare = new Square(5,4)
{
Pos = new Vector2(Width, Height) * Area
};
我想根据“mySquare”引用属性“宽度”、“高度”和“面积”。
I would like to reference a property on an object within an object initializer. The problem is that the variable does not yet exist, so I cannot reference it like normal (object.method). I do not know if there is a keyword to reference the object in creation during the object initialization.
When I compile the following code I get the error - 'The name 'Width' does not exist in the context. I understand why I get this error, but my question is: Is there any syntax to do this?
public class Square
{
public float Width { get; set; }
public float Height { get; set; }
public float Area { get { return Width * Height; } }
public Vector2 Pos { get; set; }
public Square() { }
public Square(int width, int height) { Width = width; Height = height; }
}
Square mySquare = new Square(5,4)
{
Pos = new Vector2(Width, Height) * Area
};
I would like to reference the properties "Width", "Height", and "Area" in terms of "mySquare".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能按照编写的方式执行此操作,但您可以定义
Pos
属性来执行相同的操作。当然,任何方块都具有相同的
Pos
定义。不确定这是否是您想要的。
编辑
根据您的评论,我认为您希望能够为不同的 Square 分别指定 Pos 的值。这是另一个想法。您可以向接受委托的构造函数添加第三个参数,然后构造函数可以在内部使用委托来设置属性。然后,当您创建一个新方块时,您只需传入所需表达式的 lambda 即可。像这样的事情:
然后
You can't do this as written, but you can define the
Pos
property to do the same thing. Instead ofdo this
Of course, then any square has the same definition for
Pos
. Not sure if that's what you want.Edit
Based on your comment I take it you want to be able to specify the value of Pos deferently for different Squares. Here's another idea. You could add a third argument to the constructor which takes a delegate, and then the constructor could use the delegate internally to set the property. Then when you create a new square you just pass in a lambda for the expression you want. Something like this:
then