C# 泛型 : Can I constrain to a set of classes that don't implement an interface?

标签 c# .net generics

我有 3 个基本相同但未实现接口(interface)的类,因为它们都来自不同的 Web 服务。

例如

  • Service1.Object1
  • Service2.Object1
  • Service3.Object1

它们都具有相同的属性,我正在编写一些代码,使用实现我自己的接口(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/

相关文章:

c# - 使用 MongoDB C# 查找和修改

c# - 将 DataGridViewRow 转换为 DataRow

c++ - 我应该如何避免 SQL 超时?

C# 泛型和接口(interface)以及简单的 OO

Java 泛型类数组

c# - 使用 ASP.Net Core 3.0 中的表单添加到模型的 IList

c# - 在登录 View 中找到控件

c# - IFormattable 的引用实现

c# - 将 C# 转换为 VB NET 时出现委托(delegate)错误

c# - 将 List<string> 转换为 byte[]