【发布时间】:2012-06-19 21:03:44
【问题描述】:
我有几个类,但在从其他类方法访问子类中定义的属性时遇到问题。
我有一个名为 Section 的基类和一些子类,例如SectionPlane : Section。在每个子类中,定义了一组不同的字段和属性(在SectionPlane 中,可以找到私有字段_t 和公共属性t,而在SectionExtruded : Section 中我有私有字段_A 和公共属性´ A´)。
类部分
// General section object
public abstract class Section
{
public Section()
{}
}
类平面剖面
// Section object representing a plane with thickness t
public class SectionPlane : Section
{
private double _t;
public SectionPlane(double t)
{
this.t = t;
}
public double t
{
get
{
return _t;
}
set
{
_t = value;
}
}
}
类拉伸截面
// Section object of some geometry with cross section area A extruded along the element it is assigned to.
public class SectionExtruded : Section
{
private double _A;
public SectionExtruded(double A)
{
this.A = A;
}
public double A
{
get
{
return _A;
}
set
{
_A = value;
}
}
}
当我从类Element 的任何子类尝试访问属性时会出现问题,因为这些未在基类Section 中设置,例如在元素Solid2D : Element:
类元素
public abstract class Element
{
private Section _section;
public Element(Section section)
{
this.section = section;
}
public Section section
{
get
{
return _section;
}
set
{
_section = value;
}
}
}
}
类实体二维元素
// Solid2D elements can only have sections of type SectionPlane
public class Solid2D : Element
{
public Solid2D(SectionPlane section)
: base(section)
{
}
public void Calc()
{
double t = section.t; // This results in error 'Section' does not contain a definition for 't' and no extension method 't' accepting a first argument of type 'Section' could be found (are you missing a using directive or an assembly reference?)
}
}
条形元素
// Bar elements can only have sections of type SectionExtruded
public class Solid2D : Element
{
public Solid2D(SectionExtruded section)
: base(section)
{
}
public void Calc()
{
double A = section.A; // This results in error 'Section' does not contain a definition for 'A' and no extension method 'A' accepting a first argument of type 'Section' could be found (are you missing a using directive or an assembly reference?)
}
}
有什么方法可以访问我的属性t 而不必将其包含在基类Section 中?这将非常有帮助,因为并非我将使用的所有部分都具有相同的属性。
【问题讨论】:
-
要访问
SectionPlane属性,您必须首先将对象类型转换为SectionPlane。 Tim S. 先说,但 Olivier Jacot-Descombes 的帖子在这件事上要清楚得多。 -
几周前我有同样的问题 (stackoverflow.com/questions/10804578/…),我必须说你对这个问题的解释比我的好得多。无论如何,我的解决方案是在
Solid2D中添加一个字段SectionPlane sectionPlane并在构造函数中对其进行初始化。就我而言,这已经足够了,因为它是只读的。您可能需要覆盖属性section(setter)。
标签: c# .net properties polymorphism