фанаты красивого кода.Наследование во вложенных классах C#
Я хотел бы задать свой вопрос двумя способами. Может быть, мне будет полезно понять меня.
1) Существует код из 2 классов. Один из них вложен. Вложенный класс используется для доступа к закрытым полям другого. Я хотел бы получить наследование класса 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) Существует два очень похожих «вещи» - класса А и класса В. Можно ли отделить их общую часть, а затем «унаследует» это две «вещи» от него? Например, я хотел бы добавить некоторые методы, такие как 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;
}
}
}
Благодарим за внимание.
Этот код выглядит неправильно 'foreach (AUnit unt in this.Container.AUnits) { if (unt.Name == newName) res = false; } 'вам не хватает перерыва? Это просто 'bool res =! This.Container.AUnits.Any (unt => unt.Name == newName)'? –
Похоже, да. Но эта часть кода есть только, например, как я хотел бы использовать личное поле. – JustOneQuestion