1

I want to access methods of an external class (web service) in the parent method (the web service is instantiated in the child class)

The scenario is such : I have a mother class called ConvertCurrency which takes in dollars and gives Rupees. Eg. int ConvertCurrency(int dollars);

Now there is a standard vendor out there in the market which provides a software that anybody can host on his server and create a webservice. So, lets say it is hosted at two places : www.link-A.com/service.asmx and www.link-B.com/service.asmx.

I have a parent class : CurrencyConvertor, and it has two subclasses : Convertor-A and Convertor-B.

Class CurrencyConvertor
{
    protected Object Service;

    public Convert(int dollars)
    {
        Service.ConvertCurrency(dollars);
    }
}

Class Convertor-A : CurrencyConvertor
{
    public Convertor-A()
    {
        Service = link-A.service;
    }
}

Class Convertor-B : CurrencyConvertor
{
    public Convertor-B()
    {
        Service = link-B.service;
    }
}


// based on current response-time of the two servers, we decide 
// that B is faster and hence we make the decision at run-time that we should use 
// B's service

CurrencyConvertor cc = new Convertor-B();
cc.Convert(5);

But this won't compile because the parent class doesn't know what all methods Service has and it gives the following error :

'object' does not contain a definition for 'GetSources' and no extension method 'GetSources' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

I'm wondering as to what can be a possible solution for this problem. Of course, without having to resort to creating a separate Convert function for each of the two providers.

If I can somehow make "service" Object aware of its interface (i.e. function signatures), it will work just fine.

Is there a way to get around this problem ?

4

2 回答 2

0

在 CurrencyConvertor 中创建一个名为 GetService() 的抽象方法;派生类必须以返回服务的方式实现此方法...

在货币转换器中:

 public abstract IMyNewServiceThingy GetService();

基类现在可以使用这个类来获取服务并调用它的方法

在每个派生类中:

public override IMyNewServiceThingy GetService()
{
   return Service;
}

在类上设置 Service 变量 - 级别是一个糟糕的决定,更糟糕的是,当您在创建派生类时(在构造函数中)重置它时 - 您永远无法知道当前设置了哪个 Service ..(尤其是在使用 IOC 或异步时来电)

于 2013-07-17T14:14:21.350 回答
0

我终于用反射解决了这个问题(由 Manas Agarwal 提供)

Class CurrencyConvertor cc;
cc = new Convertor-A();

BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
MethodInfo m = cc.type.GetMethod(MethodName, flags);
response = (string)m.Invoke(cc.Service, Parameters);
于 2013-07-19T07:36:49.677 回答