作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有 3 个基本相同但未实现接口(interface)的类,因为它们都来自不同的 Web 服务。
例如
它们都具有相同的属性,我正在编写一些代码,使用实现我自己的接口(interface) 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);
}
有什么想法吗?
编辑:我不想更改每个网络服务的 Reference.cs 文件,因为只需要团队成员更新网络引用和 BAM!损坏的代码。
最佳答案
假设生成的类是部分的,您可以创建一个接口(interface),然后添加另一个部分的源文件,使您生成的类实现该接口(interface)。然后你可以像往常一样通过接口(interface)进行约束。无需更改实际生成的代码:)
关于C# 泛型 : Can I constrain to a set of classes that don't implement an interface?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/218888/
我是一名优秀的程序员,十分优秀!