我需要从父类(super class)返回“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类是父类(super class),B类是从A继承的子类。 这两个类实现接口(interface) A 和 B。
我需要调用“x.Format().PrintB();”只是为了格式化字符串。
换句话说,我需要在 Format() 函数中返回相同的对象,并且根据 Format() 中的更改我需要更改 PrintB 行为。
因此,如果我创建了新的类 D 并继承了 A,我也想基于 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();
}
}
关于c# - 从父类(super class) C# 返回子类的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55478655/