通用对象的创建模式

问题描述 投票:0回答:1

有人可以帮助您在以下场景中返回具体实现的最佳方式。说我有:

public interface IThing<TInput> where TInput : RequestBase
{
    string Process(T input);
}

然后是多个实现:

public class Thing1<T> : IThing<T> where T : ReqThing1
public class Thing2<T> : IThing<T> where T : ReqThing2

在我的调用类中,包装这些类的构造并以干净,可测试的方式返回我想要的Thing的最佳方法是什么?谢谢

c# asp.net-core design-patterns asp.net-core-2.1
1个回答
1
投票

我不太明白你想要什么,但这是一个想法:

public abstract class RequestBase
{
}

public class ReqThing1 : RequestBase
{
}

public class ReqThing2 : RequestBase
{
}

public interface IThing<T> where T : RequestBase
{
    string Process(T input);
}

public class Thing1 : IThing<ReqThing1>
{
    public string Process(ReqThing1 input)
    {
        throw new System.NotImplementedException();
    }
}

public class Thing2 : IThing<ReqThing2>
{
    public string Process(ReqThing2 input)
    {
        throw new System.NotImplementedException();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var thing1 = new Thing1();
        var thing2 = new Thing2();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.