c# - 从父类(super class) C# 返回子类的 "this"

标签 c# oop

我需要从父类(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/

相关文章:

c# - Try/Catch 在 VS 2010 中未捕获异常

javascript - 如何在 Jquery 中将 MVC 表单序列化为 JSON

c# - ASP.NET 自动执行页面

PHP 命名空间自动加载

java - RecyclerView的OnScrollListener是抽象类?

php - 试图用 Mysqli 插入我得到 "Using $this when not in object context in"

C#检查哪个整数更大

c# - 亚马逊产品 API 是否有最新的 c# 示例?

java - 属性的 OOP 继承

php - 逐步将项目添加到站点