在多个服务和.net版本之间重用类型

时间:2019-05-25 17:46:25

标签: c# web-services .net-4.0 .net-3.5

我有全部引用Common.dll的服务(Service1,Service2等),所有这些服务均位于 .Net 4.0 中,并且在重用使用者的类型时遇到了麻烦服务。


Common.dll具有

Identifier {
    int Id;
    string Type;
}

每个服务都实现

byte[] Get(Common.Identifier);
string Test();

服务的使用者( .Net3.5 )在reference.cs中生成代码。

class Service1 {
    byte[] Get(Service1.Identifier);
    string Test();  
}

class Service2 {
    byte[] Get(Service2.Identifier);
    string Test();  
}

我通过创建一个界面将它们绑在一起 将接口添加到部分类中,但只能使其用于Test()调用

public interface IService {
    //byte[] Get(Service2.Identifier);
    string Test();  
}

public partial class Service1 : IService;
public partial class Service2 : IService;

这样,我可以互换使用服务。 我计划创建更多用作基本插件以集成到不同系统的

IService GetService(string provider) {
    switch (provider) {
        case "Service1":
            return (IService)new Service1();

        case "Service2":
            return (IService)new Service2();
    }
}

GetService.Test() //works perfectly.

我的问题是如何以一种无需编写大量代码即可使用Get(?? Identifier)的方式定义,修饰“标识符”。

我现在唯一想到的方法是创建一个接口IIdentifier,然后将其添加到部分类中

public partial class Service1 : IService {
    byte[] Get(IIdentifier id) {
        return this.Get(new Service1.Identifier() { Id = id.Id, Type = id.Type});
}

但是有很多电话,我不想全部打包。我确定我只是缺少一些简单的东西,感谢您可以提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

C#没有提供将不同类型用作同一类型的方法,即使在特定情况下成员相同也是如此。要解决此问题,您可能需要重写服务以使用共享类或将彼此映射的类,可能需要添加扩展方法以使代码看起来像Get接受相同的类型。

如果您不需要传递唯一参数,而只需调用非虚拟/非接口方法,则可以使用dynamicdynamic service = ....; service.Get();),它最接近鸭子输入,如您所愿

答案 1 :(得分:0)

我是从错误的角度进行尝试的,而我尝试这样做的方式却无法像Alexei所指出的那样起作用。

我设法通过.net 3.5(而不是4.0)进行编译,从而使一切正常工作并重用了common.dll中的类。

.Net 4.0向后兼容3.5,因此我能够从服务中引用3.5 common.dll,这使我的3.5代码可以引用common.dll,从而重新使用类型。

相关问题