如何访问子对象属性

时间:2011-04-22 04:24:03

标签: c# inheritance parent-child

我很抱歉,如果之前有人问过,但我真的不知道我是否正确地说出了这个问题:

所以,让我说我有这个课程:

class Shape{
int Area
}

class Triangle:Shape{
string type_of_triangle;
}

class Star:Shape{
int Number_of_Points;
}

和一个返回形状类型List的函数,其中包含三角形和形状对象。当我尝试访问三角形或星形属性时,visual studio只允许我访问父级的属性。

所以,基本上我的问题是:如果对象存储在父类型变量中,我如何访问子属性?

2 个答案:

答案 0 :(得分:3)

Shape unknownShape = new Triangle();

if(unknownShape is Triangle){
    ((Triangle)unknownShape).type_of_triangle;
}

答案 1 :(得分:-1)

我建议你多考虑一下你的类层次结构的设计。在我的脑海中,我建议您可以将您为派生形状定义的所有属性放在父级中。此外,您可能需要考虑使用其中一些返回值的方法。

虽然它不是您当前示例的一部分,但任何形状(包括圆形)都具有有限数量的点(圆圈只有零)。通用的“shape_family”属性可能表示形状类的特定派生(“Triangle”,“Star”等)的字符串分类。

shape_subtype可能代表特定的变化(“右三角”,“Isoceles三角”等)。然后,如果您将点定义为POINTS并将它们添加到列表中,您不仅会为它们指定位置(如果这不超出您的程序范围),但您也会有计数。从那里你可以找出一些额外的逻辑来映射边/垂直,并计算区域,周长等等。

考虑(但请注意,我现在只是从vb.net分支到C#和Java,所以如果我在这里编写代码,请尝试关注类结构,而不是我的语法......):

编辑:4/22/2011 7:41 AM - 哎呀。忘了让Class抽象化。如果类上的方法被定义为“抽象”,那么类本身也必须是抽象的,这意味着抽象基础不能直接实例化。这是关于抽象类和方法/

的更多信息的link
public abstract class Shape
{ 
    int Area; 
    string shape_family;
    string shape_subtype;
    list<point> Points

    public int number_of_points()    
    {
        return points.count
    }        
    public abstract int perimeter_lenngth()
    public abstract int area()
}  

class Triangle : Shape { 

    //Example of Triangle-specific implementation:
    public override int perimiter_length {
       //You code to obtain and compute the lengths of the sides
    }

    //Example of Triangle-specific implementation:
    public override int area {
        //Your code to obtain and compute        
    }
}

class Star : Shape{

    //Example of Star-specific implementation:
    public override int perimiter_length {
       //Your code to obtain and compute the lengths of the sides
    }

    //Example of Star-specific implementation:
    public override int area {
        //Your code to obtain and compute        
    }
}

class Circle : Shape {
    point center;
    int radius

    // Example of Circle-specific implementation:
    public override int perimiter_length {
        return 2*3.14*radius
    }

    // Example of Circle-specific implementation:
    public override int area {
        return 3.14*radius^2
    }
}
相关问题