我有3个基本相同但没有实现接口的类,因为它们都来自不同的Web服务.
例如
它们都具有相同的属性,我正在编写一些代码,使用实现我自己的接口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());
}
Run Code Online (Sandbox Code Playgroud)
我的客户端代码如下:
//properties is an array of my intermediary objects
Object1[] props = ServiceObjectFactory.CreateObject1<Object1>(properties);
Run Code Online (Sandbox Code Playgroud)
我想要做的是摆脱CheckObject1Types方法并使用约束,以便在类型无效时我得到构建错误,因为目前我可以使用任何类型调用此方法,并且抛出ArgumentException CheckObject1Types方法.
所以我想做一些像:
public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new(), Service1.Object1|Service2.Object1|Service3.Object1
{
return CreateObjectArray<T>(properties);
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
编辑:我不想更改每个Web服务的Reference.cs文件,因为只需要一个队友来更新Web引用和BAM!破碎的代码.