gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:18:19 24 4
gpt4 key购买 nike

我有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com