[英]Return “this” of the subclass from superclass C#
我需要從超類返回“this”或子類實例。
interface IA
{
IA Format();
void Print();
}
interface IB
{
IA Format();
void Print();
void PrintB();
}
abstract class A : IA
{
protected bool isFormated;
public IA Format()
{
isFormated = true;
return this;
}
virtual public void Print()
{
Console.WriteLine("this is A");
}
}
class B : A, IB
{
override public void Print()
{
Console.WriteLine("this is B");
}
public void PrintB()
{
if (isFormated)
{
Console.WriteLine("this is formated B");
}
else
{
Console.WriteLine("this is B");
}
}
}
class Program
{
static void Main(string[] args)
{
var x = new B();
x.Format().PrintB();
}
}
我有兩個類,類A是超類,類B是從A繼承的子類。這兩個類實現了接口A和B.
我需要調用'x.Format()。PrintB();' 只是格式化字符串。
換句話說,我需要在Format()函數中返回相同的對象,並根據Format()中的更改我需要更改PrintB行為。
因此,如果我創建了新的D類並且繼承了AI,則希望使用基於isFormated的不同行為實現PrintD。
我把A作為通用類取T型,我把它作為T返回
interface IA<T> where T : class
{
T Format { get; }
void Print();
}
abstract class A<T> : IA<T> where T : class
{
protected bool isFormated;
public T Format
{
get
{
isFormated = true;
return this as T;
}
}
virtual public void Print()
{
Console.WriteLine("this is A");
}
}
interface IB
{
void Print();
void PrintB();
}
class B : A<B>, IB
{
override public void Print()
{
Console.WriteLine("this is B");
}
public void PrintB()
{
if (isFormated)
{
Console.WriteLine("this is formated B");
}
else
{
Console.WriteLine("this is B");
}
}
}
class Program
{
static void Main(string[] args)
{
var x = new B();
x.Format.PrintB();
}
}
當你調用x.Next()
,它返回一個實現IA
的東西的實例。 這可能是A
, B
或任何其他實現IA
類,但由於它返回IA
,其他類不知道具體類型是什么。 這通常是故意的。 如果其他類不知道IA
的實現是什么,那么你可以用另一個替換。
但是,由於Next
返回IA
,因此只有IA
具有PrintB
方法才能調用PrintB
,如下所示:
public interface IA
{
void PrintB();
}
如果A
實現IA
則它必須具有PrintB
方法。 但因為它是一個abstract
類,所以該方法可以是抽象的。 這意味着A
並沒有真正實現該方法。 從A
繼承的非抽象類將需要實現它。
這看起來像這樣:
abstract class A : IA
{
public IA Next()
{
return this;
}
virtual public void Print()
{
Console.WriteLine("this is A");
}
public abstract void PrintB();
}
PrintB
不一定是抽象的。 A
可以實現它。 它可以是虛擬的,其他類可以覆蓋它。 或者既不是抽象也不是虛擬,其他類也無法覆蓋它。
現在,當您聲明B : A
,編譯器將需要B
來實現PrintB
。
然后你可以調用Next().PrintB()
因為Next()
返回IA
而IA
有一個PrintB
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.