简体   繁体   English

寻找接口/抽象,但方法返回不同的类型

[英]Looking for an interface/abstract but with methods returning different types

I am looking for a design pattern for a base class that forces all derived classes to implement all base class methods, while the methods in the derived classes have different return types. 我正在寻找一个基类的设计模式,该模式强制所有派生类实现所有基类方法,而派生类中的方法具有不同的返回类型。 The scenario is a generic MemoryObject class (interface/abstract), keeping and returning whatever kind of objects in/from memory. 该方案是一个泛型MemoryObject类(接口/抽象),用于在内存中或从内存中返回任何类型的对象。 But the derived classes (static/sealed/singleton) should return the correct type. 但是派生类(静态/密封/单个)应返回正确的类型。

So the requirements are - force all derived classes to implement all properties and methods of the base class - methods in derived classes must return correct type 因此,要求是-强制所有派生类实现基类的所有属性和方法-派生类中的方法必须返回正确的类型

Here's some sample code, not compilable, but for illustration: 这是一些示例代码,不可编译,但仅用于说明:

    public interface MemoryObject
    {
         object FromMemory { get; }
         //... other properties and methods
    }

    public sealed class MemoryObjectA : MemoryObject
    {
        public static List<string> FromMemory 
        {
            get { return new List<string>(); }
        }

        //... other properties and methods
    }

    public sealed class MemoryObjectB : MemoryObject
    {
        public static DataTable FromMemory 
        {
            get { return new DataTable(); }
        }

        //... other properties and methods
    }

Thanks for your suggestions in advance! 预先感谢您的建议!

It sounds like you just need to make it generic: 听起来您只需要使其通用即可:

public interface MemoryObject<T>
{
     T FromMemory { get; }
     //... other properties and methods
}

public class MemoryObjectA : MemoryObject<List<string>> { ... }
public class MemoryObjectB : MemoryObject<DataTable> { ... }

Note that the implementation methods will have to be instance methods, not static methods. 注意,实现方法必须是实例方法, 而不是静态方法。 (You can make the implementations singletons though, should you wish.) (不过,您可以根据需要使实现单例。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM