[英]Inheritance in nested classes C#
精美代码的粉丝。
我想通过两种方式问我的问题。 可能对我有所了解。
1)有2类代码。 其中之一是嵌套的。 嵌套类用于访问另一类的私有字段。 我想继承具有相同功能的B:A {class BUnit:AUnit {}}类,但在B和BUnits类中还有更多方法和字段。 怎么做?
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Add();
a.Add();
a.Add();
bool res=a[0].Rename("1");//res=true;
res = a[1].Rename("1");//res= false;
Console.ReadKey();
}
}
class A
{
private List<AUnit> AUnits;
public AUnit this[int index] {get {return AUnits[index];}}
public A()//ctor
{
AUnits = new List<AUnit>();
}
public void Add()
{
this.AUnits.Add(new AUnit(this));
}
public class AUnit
{
private string NamePr;
private A Container;
public AUnit(A container)//ctor
{
NamePr = "Default";
this.Container = container;
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (AUnit unt in this.Container.AUnits)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
2)有两个非常相似的“事物” — A类和B类。是否可以将它们的共同部分分开,然后从中“继承”这两个“事物”? 例如,我想添加一些方法,例如GetUnitsCount()或RemoveUnit(),并且这两种方法都是通用的。 因此,我应该将此方法“复制粘贴”到A和B,但这不是一个好主意。 最好一次更改一次它们的公用部分。 做到这一点并不重要-继承,接口或其他任何东西。 重要-如何?
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Add();
a[0].objB.Add();
a[0].objB.Add();
a[0].objB[0].Val1 = 1;
int res = a[0].objB[0].Val1 + a[0].objB[0].Val2;
Console.ReadKey();
}
}
class A
{
private List<AUnit> Units;
public AUnit this[int index] {get {return Units[index];}}
public A()//ctor
{
Units = new List<AUnit>();
}
public void Add()
{
this.Units.Add(new AUnit(this));
}
public class AUnit
{
private string NamePr;
private A Container;
public B objB;
public AUnit(A container)//ctor
{
NamePr = "Default";
this.Container = container;
this.objB = new B();
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (AUnit unt in this.Container.Units)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
class B
{
private List<BUnit> Units;
public BUnit this[int index] { get { return Units[index]; } }
public B()//ctor
{
Units = new List<BUnit>();
}
public void Add()
{
this.Units.Add(new BUnit(this));
}
public class BUnit
{
private string NamePr;
private B Container;
public int Val1{get;set;}
public int Val2{get;set;}
public BUnit(B container)//ctor
{
NamePr = "Default";
this.Container = container;
this.Val1 = 10;
this.Val2 = 17;
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (BUnit unt in this.Container.Units)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
谢谢您的关注。
要回答第一个问题,让BUnit
从AUnit
继承的唯一需要AUnit
就是限定 AUnit
资格 :
public class BUnit : A.AUnit
{
....
}
从那里开始,我相信您的问题是关于基本继承的,对于嵌套类而言,基本继承没有什么不同。 嵌套类仅用于组织-当您继承“包含”类时,它们不会被继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.