如何访问子对象属性
如果之前有人问过这个问题,我很抱歉,但我真的不知道我是否正确地表达了这个问题:
所以,假设我有这个类:
class Shape{
int Area
}
class Triangle:Shape{
string type_of_triangle;
}
class Star:Shape{
int Number_of_Points;
}
以及一个返回包含三角形和形状的形状类型列表的函数里面的物体。当我尝试访问三角形或星形的属性时,Visual Studio 只允许我访问父级的属性。
所以,基本上我的问题是:如果对象存储在父类型变量中,我如何访问子对象的属性?
i am sorry if this has been asked before, but i don't really know if i'm phrasing the question right:
So, let's say i have this classes:
class Shape{
int Area
}
class Triangle:Shape{
string type_of_triangle;
}
class Star:Shape{
int Number_of_Points;
}
and a function that returns a shape typed List wich contains both triangle and shape objects in it. when i try to access triangle's or star's properties, visual studio only let's me access the parent's properties.
So, basically my question is: How can i access the child's properties if the objects are stored in a parent-type variable??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议多考虑一下类层次结构的设计。我突然建议您可以将为派生形状定义的所有属性放在父级中。此外,您可能需要考虑使其中一些方法返回值。
虽然它不是当前示例的一部分,但任何形状(包括圆形)都具有有限数量的点(圆形只有零)。通用的“shape_family”属性可以表示形状类的特定派生的字符串分类(“三角形”、“星形”等)。
shape_subtype 可能代表特定的变体(“直角三角形”、“等腰三角形”等)。然后,如果您将点定义为 POINTS 并将它们添加到列表中,您不仅会为它们指定位置(如果这不超出您的程序范围),而且还会有一个计数。从那里你可能可以制定一些额外的逻辑来映射边/垂直,并计算面积、周长等。
考虑一下(但请注意,我现在只是从 vb.net 分支到 C# 和 Java,所以如果我在这里破坏代码,尝试关注类结构,而不是我的语法。):
编辑:2011 年 4 月 22 日上午 7:41 - 哎呀。忘记使类抽象。如果类上的方法被定义为“抽象”,那么该类本身也必须是抽象的,这意味着抽象基不能直接实例化。这是一个链接有关抽象类和方法的更多信息/
I would suggest giving a little more thought to the design of you class hierarchy. Off the top of my head I would propose you can place all of the properties you have defined for your derived shapes within the parent. Further, you might want to consider making some of them methods which return values.
While it is not part of your current example, any shape, including a circle has a finite number of points (a circle simply has zero). A generic "shape_family" property might represent the string classification for the specific derivation of the shape class ("Triangle", "Star", etc).
The shape_subtype might represent specific variations ("Right Triangle", "Isoceles Triangle", etc.). Then, if you define the points as, well, POINTS and add them to a list, you will not only have specified locations for them (if that is not beyond the scope of your program), but you will have a count as well. From there you can probably work out some additional logic to map the sides/verticals, and compute such things as Area, perimeter, etc.
Consider (but please note that I am only now branching into C# and Java from vb.net, so if I butcher the code here, try to focus on the class structure, NOT my syntax . . .):
Edit: 4/22/2011 7:41 AM - Ooops. Forgot to make the Class abstract. If methods on a class are defined as "abstract", then the class itself must be abstract as well, meaning the abstract base cannot be directly instantiated. Here is a link to more info on abstract classes and methods/