c# - 从超类 C# 返回子类的“this”
问题描述
我需要从超类返回“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();
}
}
推荐阅读
- angular - Angular 6 - Child-Parent-Child 交互:值在 html 中更新,而不是在 .ts 程序中
- javascript - 循环遍历两个数组并使用 javascript 获得所需的输出
- c++ - 为什么 'apt-file list' 列出不在主机上的 *.so 文件?我链接到哪一个?
- jquery - Tabify Your SharePoint Forms: list to tabs (需要添加更多到 jquery 脚本)
- python - 无法解析 json 文件:json.decoder.JSONDecodeError: Extra data。
- laravel - Laravel 5 包的可定制模型文件
- corda - 现金流量测试的保险柜查询不起作用
- django - 如何在html中显示verbose_name?
- javascript - 在 React 中下载 JSON
- direct2d - Direct2D 中几何组合的内部结构 - 它是如何工作的?