【发布时间】:2019-04-02 15:40:34
【问题描述】:
我需要从超类返回“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 类并继承了 A,我也想基于 isFormated 实现具有不同行为的 PrintD。
【问题讨论】:
-
您正在返回
B的实例 - 这里只有一个实例在起作用 - 但输入为IA所以它没有PrintB方法。你能详细解释一下你真正想要实现的目标吗? -
我正在尝试返回 B 的“this”,但我的代码中缺少某些内容。我也应该在子类中实现“Next()”吗?
-
IA和IB之间有关系吗? -
当您已经将实例存储在
x中时,为什么还需要使用this? -
@Svarr 我有这方面的用例,但我试图让这个例子变得简单。