我希望有一个基类,其中包含一个嵌套类-并展开子类中的嵌套类:
出于某种原因-我无法访问嵌套派生类新(添加的)属性:
public class BaseClass
{
public NestedClass nestedClass {get; set;}
public BaseClass()
{
nestedClass = new NestedClass();
}
public int baseproperty {get; set;}
public class NestedClass
{
public int NestedProperty {get; set;}
}
}
public class Derived : BaseClass
{
public class NestedClass
{
public DeeperNestedClass deeper {get; set;}
public NestedClass()
{
deeper = new DeeperNestedClass();
}
public class DeeperNestedClass
{
public int VeryDeepPropery {get; set;}
}
}
}
Derived MyDerived = new Derived();
MyDerived.nestedClass.deeper <----- Doesn't recognized !
*编辑-修复了基类中缺少的“类”
最佳答案
你基本上有三个问题:
1)实际上,必须从Derived.NestedClass
派生BaseClass.NestedClass
。
2)您的属性BaseClass.nestedClass
将始终具有BaseClass.NestedClass
类型,因此您需要将其转换为访问deeper
属性。
3)在访问BaseClass.nestedClass
时,必须确保属性Derived.NestedClass
实际包含Derived
类型的对象。
public class BaseClass {
public NestedClass nestedClass { get; set; }
public BaseClass() {
nestedClass = new NestedClass();
}
public int baseproperty { get; set; }
public class NestedClass {
public int NestedProperty { get; set; }
}
}
public class Derived : BaseClass {
public Derived() {
nestedClass = new NestedClass();
}
public class NestedClass : BaseClass.NestedClass {
public DeeperNestedClass deeper { get; set; }
public NestedClass() {
deeper = new DeeperNestedClass();
}
public class DeeperNestedClass {
public int VeryDeepPropery { get; set; }
}
}
}
class Program {
static void Main(string[] args) {
Derived derived = new Derived();
BaseClass.NestedClass nestedBase = derived.nestedClass;
Derived.NestedClass nestedDerived = (Derived.NestedClass)nestedBase;
Derived.NestedClass.DeeperNestedClass deeper = nestedDerived.deeper;
int property = deeper.VeryDeepPropery;
}
}
在评论中讨论后编辑:
也许这样简单的事情对你有用?
public class OuterClass {
public OuterClass() {
nestedClass = new NestedClass();
}
public int baseproperty { get; set; }
public NestedClass nestedClass { get; set; }
}
public class NestedClass {
public NestedClass() {
deeper = new DeeperNestedClass();
}
public int NestedProperty { get; set; }
public DeeperNestedClass deeper { get; set; }
}
public class DeeperNestedClass {
public int VeryDeepPropery { get; set; }
}
class Program {
static void Main(string[] args) {
OuterClass outer = new OuterClass();
int property = outer.nestedClass.deeper.VeryDeepPropery;
}
}