C#代码来处理不同的班级,同样的方法名称 [英] C# code to handle different classes with same method names

查看:90
本文介绍了C#代码来处理不同的班级,同样的方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有两个不同的C#类 A B ,虽然不是来自同一个基类派生办分享一些对方法相同的名称。例如,这两个类有一个连接断开方法,以及其他几个人。我希望能够编写一次代码,将与这两种类型。

Let's say you have two different C# classes A and B that while not deriving from the same base class do share some of the same names for methods. For example, both classes have a connect and a disconnect method, as well as several others. I want to be able to write code once that will work with both types.

下面是我想要做什么一个简单的例子:

Here is a simplified example of what I would like to do:

public void make_connection(Object x)
{
  x.connect() ;
  // Do some more stuff...
  x.disconnect() ;
  return ;
}



当然,这不会编译因为Object类没有一个连接断开方法。

有没有办法做到这一点?

Is there a way to do this?

更新。我应该让这个明确从一开始:我只对A中的DLL和B而不是源

UPDATE. I should have made this clear from the start: I only have the DLLs for A and B and not the source.

推荐答案

您可以用一个接口来完成你想做的事情。

You can use an interface to accomplish what you want to do.

interface IConnectable
{
    void Connect();

    void Disconnect();
}



两者 A B 应实施 IConnectable 。然后使用 IConnectable 而不是对象作为参数类型为你的方法,你应该准备就绪。

Both A and B should implement IConnectable. Then use IConnectable instead of Object as the parameter type for your method and you should be all set.

public void MakeConnection(IConnectable connectable)
{
    connectable.Connect();

    // Do some more stuff...

    connectable.Disconnect();
}



编辑:因为你没有源代码,你有两个选择:

Since you don't have the source code, you have a couple of options:


  1. 使用动态使用最多的解决方案关键词,(如果你使用的是.NET 4.0)

  2. 使用的铸造用史蒂夫的解决方案和如果 / 其他语句

  3. A 和 b ,并让他们实现接口(或使用通用抽象基类为他们)

  1. Use Max's solution of using the dynamic keyword, (if you are using .NET 4.0)
  2. Use Steve's solution of using casting and if/else statements
  3. Create wrapper classes for A and B and have them implement the interface (or use common abstract base class for them)

例如:

class AWrapper : IConnectable
{
    private A obj;

    public AWrapper(A obj)
    {
        this.obj = obj;
    }

    public void Connect()
    {
        this.obj.Connect();
    }

    public void Disconnect()
    {
        this.obj.Disconnect();
    }

    // other methods as necessary
}

BWrapper 有异曲同工之处,只是用 B 而不是 A

(BWrapper would be similar, just using B instead of A)

然后,你可以创建包装和它们传递到的makeConnection 。你想怎么办呢这是由你决定。根据您的情况,一种方法可能比其他人更容易。

Then you could create the wrappers and pass them into MakeConnection. It's up to you how you want to do it. Depending on your situation, one method may be easier than the others.

这篇关于C#代码来处理不同的班级,同样的方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆