美丽密码的粉丝们。
我想用两种方式问我的问题。也许理解我是有用的。
1)有两个类的代码。其中一个是嵌套的。嵌套类用于访问其他字段的私有字段。我想继承B类:a类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(),这两种方法都很常见。所以我应该“CopyPaste”这个方法到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;
}
}
}谢谢你的关心。
发布于 2016-09-30 20:38:36
要回答您的第一个问题,BUnit从AUnit继承的唯一需要是对AUnit进行限定。
public class BUnit : A.AUnit
{
....
}从这里开始,我相信您的问题是关于基本继承的,它对于嵌套类没有什么不同。嵌套类纯粹用于组织--当您继承“包含”类时,它们不会被继承。
https://stackoverflow.com/questions/39799668
复制相似问题