我有几个类,我在尝试从其他类方法中访问子类定义的属性时遇到了问题。
我有一个名为“Section”的基类和一些子类,例如“SectionPlane : Section”。每个子类都定义了不同的字段和属性(在“SectionPlane”中,可以找到私有字段“_t”和公共属性“t”,而在“SectionExtruded : Section”中,我有私有字段“A”和公共属性“A”)。 类Section:
我有一个名为“Section”的基类和一些子类,例如“SectionPlane : Section”。每个子类都定义了不同的字段和属性(在“SectionPlane”中,可以找到私有字段“_t”和公共属性“t”,而在“SectionExtruded : Section”中,我有私有字段“A”和公共属性“A”)。 类Section:
// 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
中:
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 Element
// 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的帖子更加清晰明了。 - Trisped并在构造函数中初始化它。在我的情况下,这已经足够了,因为它是只读的。您可能需要重写属性
section`(setter)。 - Paul B.