我有几个类,并且在从其他类方法访问子类中定义的属性时遇到问题。
我有一个名为的基类Section
和一些子类,例如SectionPlane : Section
. 在每个子类中,定义了一组不同的字段和属性(在 中SectionPlane
,可以找到私有字段_t
和公共属性,而在我有私有字段和公共属性“A”)。t
SectionExtruded : Section
_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;
}
}
}
}
类实体 2D 元素
// 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
?这将非常有帮助,因为并非我将使用的所有部分都具有相同的属性。