【发布时间】:2008-10-20 15:47:26
【问题描述】:
我有 3 个基本相同但没有实现接口的类,因为它们都来自不同的 Web 服务。
例如
- Service1.Object1
- Service2.Object1
- Service3.Object1
它们都具有相同的属性,我正在编写一些代码以使用实现我自己的接口 IObject1 的中间对象将它们相互映射
我已经使用泛型完成了这项工作
public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new()
{
//Check the type is allowed
CheckObject1Types("CreateObject1<T>(IObject1[])", typeof(T));
return CreateObjectArray<T>(properties);
}
private static void CheckObject1Types(string method, Type type)
{
if (type == typeof(Service1.Object1)
|| type == typeof(Service2.Object1)
|| type == typeof(Service3.Object1)
|| type == typeof(Service1.Object1[])
|| type == typeof(Service2.Object1[])
|| type == typeof(Service3.Object1[]))
{
return;
}
throw new ArgumentException("Incorrect type passed to ServiceObjectFactory::" + method + ". Type:" + type.ToString());
}
我的客户端代码如下:
//properties is an array of my intermediary objects
Object1[] props = ServiceObjectFactory.CreateObject1<Object1>(properties);
我想要做的是摆脱 CheckObject1Types 方法并改用约束,以便在类型无效时得到构建错误,因为目前我可以使用任何类型调用此方法并且 ArgumentException 是由 CheckObject1Types 方法抛出。
所以我想做这样的事情:
public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new(), Service1.Object1|Service2.Object1|Service3.Object1
{
return CreateObjectArray<T>(properties);
}
有什么想法吗?
编辑:我不想更改每个 Web 服务的 Reference.cs 文件,因为只需要一个队友来更新 Web 引用和 BAM!损坏的代码。
【问题讨论】:
-
我刚刚注意到我可以通过将检查类型代码从 && 更改为 || 来提高效率和 != 到 == 在任何人指出这一点之前。