你可以把工厂注入你的
Thingdoerbase公司
:
您的iRequest接口:
interface IRequest { }
interface IRequest<T>:IRequest
{
T GenericParm { get; set; }
int IntParm { get; set; }
}
你的基础班:
abstract class ThingDoerBase : IDoStuff
{
private Func<IRequest> _factory;
protected ThingDoerBase(Func<IRequest> factory) => _factory = factory;
// simplifed but default for the integer parm
public virtual string DoThingOne<T>(T parm) => DoThingOne(parm, 25);
public virtual string DoThingOne<T>(T parm, int anotherParm)
{
if(!(_factory() is IRequest<T> request))
throw new InvalidOperationException();
request.GenericParm = parm;
request.IntParm = anotherParm;
return SendRequest(request);
}
public abstract string SendRequest<T>(IRequest<T> request);
public void ChangeRequestFactory(Func<IRequest> factory) => _factory = factory;
}
示例实现:
class Foo :ThingDoerBase{
public Foo(Func<IRequest> factory) : base(factory) { }
public override string SendRequest<T>(IRequest<T> request) =>
throw new NotImplementedException();
}
和测试:
var foo = new Foo(() => new Imp1Request<int>());
foo.DoThingOne(1);
foo.DoThingOne("lol"); //will throw InvalidOperationException
foo.ChangeRequestFactory(() => new Imp1Request<string>());
foo.DoThingOne(1);//will throw InvalidOperationException
foo.DoThingOne("lol");