gpt4 book ai didi

c# - 在派生类 C# 中扩展嵌套类

转载 作者:太空狗 更新时间:2023-10-30 00:31:27 25 4
gpt4 key购买 nike

我想要一个基类,里面有一个嵌套类 - 并在子类中扩展嵌套类:由于某种原因 - 我无法访问嵌套派生类的新(添加)属性:

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) 您实际上必须从 BaseClass.NestedClass 派生 Derived.NestedClass

2) 您的属性 BaseClass.nestedClass 将始终具有 BaseClass.NestedClass 的类型,因此您需要转换它以访问更深层次的属性(property)。

3) 当在 Derived 中访问时,您必须确保 BaseClass.nestedClass 属性实际上包含 Derived.NestedClass 类型的对象>.

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;
}
}

关于c# - 在派生类 C# 中扩展嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com