首页 > 解决方案 > 从超类 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。

标签: c#oop

解决方案


我将 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();
    }
}

推荐阅读