【发布时间】:2012-03-22 22:04:09
【问题描述】:
对不起,如果这个问题已经得到回答,但我认为我实际上缺乏正确提出这个问题的正规教育,因此也缺乏成功搜索它的正确标准。
我有一个 API,它有几个调用几乎做同样的事情,但使用不同的方法作用于不同的输入对象,但总是形成相同的接口。我想从 API 方法调用过程中取出剪切和粘贴方面,以便公共代码在所有方法调用中都完成相同的操作。我已经设法为输入和输出对象使用泛型获得了一个可行的解决方案,并且正在引用要从字符串调用的方法名称。我希望对方法的引用是强类型而不是基于字符串的,以便在重构时重命名方法名称不会潜在地让方法名称的“魔术”字符串在运行时等待爆炸。
下面是我想要实现的一个非常简化的版本。
class ARequest { };
class AResponse { };
class BRequest { };
class BResponse { };
interface IWorker
{
AResponse DoA(ARequest aRequest);
BResponse DoB(BRequest bRequest);
}
class Worker : IWorker
{
public AResponse DoA(ARequest aRequest)
{
return new AResponse();
}
public BResponse DoB(BRequest bRequest)
{
return new BResponse();
}
}
class Program
{
static void Main(string[] args)
{
// current concrete copy & paste implementation
var a1 = API.DoA(new ARequest { });
var b1 = API.DoB(new BRequest { });
// new generic implementation
var a2 = API.DoA2(new ARequest { });
var b2 = API.DoB2(new BRequest { });
}
}
static class API
{
// current concrete copy & paste implementation
public static AResponse DoA(ARequest aRequest)
{
// lots of common code for logging & preperation
var worker = GetWorker();
return worker.DoA(aRequest);
}
public static BResponse DoB(BRequest bRequest)
{
// lots of common code for logging & preperation
var worker = GetWorker();
return worker.DoB(bRequest);
}
private static IWorker GetWorker()
{
return new Worker();
}
// new generic implementation Attempt
public static AResponse DoA2(ARequest aRequest)
{
return DoGen<ARequest, AResponse>(aRequest, "DoA"); // how to make references to DoA and DoB methods on the IWorker strongly typed?
}
public static BResponse DoB2(BRequest bRequest)
{
return DoGen<BRequest, BResponse>(bRequest, "DoB"); // how to make references to DoA and DoB methods on the IWorker strongly typed?
}
public static TResponse DoGen<TRequest, TResponse>(TRequest requestObj, string methodname)
where TRequest : class
where TResponse : class
{
// lots of common code for logging & preperation
var worker = GetWorker();
var mi = worker.GetType().GetMethod(methodname);
var result = mi.Invoke(worker, new Object[] { requestObj });
return result as TResponse;
}
}
【问题讨论】:
-
响应类型是否有任何关联?
-
看看这篇博文,它描述了一个可以满足你需要的模型:cuttingedge.it/blogs/steven/pivot/entry.php?id=92
-
Foo42:它们在最终实现中有一些来自公共基类的公共字段。在示例中,它们不相关。
标签: c# reflection interface strongly-typed-view strong-typing