我简化了我的内容:
class A : SomeClassICantAccess
{
IVIClass ivi = new IVIClass();
public A()
{
string address = "1111";
ivi.Initialize(address);
}
public void SendCommand(string cmd)
{
ivi.Send(cmd);
}
}
class B : SomeClassICantAccess
{
IVIClass ivi = new IVIClass();
public B()
{
string address = "2222";
ivi.Initialize(address);
}
public void SendCommand(string cmd)
{
ivi.Send(cmd);
}
}
class Main()
{
//I want my main to keep this format
A a = new A();
B b = new B();
a.SendCommand("commands");
b.SendCommand("commands");
}
如您所见,类A
和B
具有相同的SendCommand()
方法,但由于它们的ivi
初始化为不同的地址,因此命令会被发送到不同的仪器
在两个不同的类中复制粘贴相同的方法似乎是错误的。但是我真的希望我的Main()
看起来像现在这样 - 以便明确SendCommand()
是指仪器A还是仪器B。
如何合并?
答案 0 :(得分:3)
如果这是您的实际情况,则不需要两个课程,您只能处理A
:
A
的类定义:
class A()
{
IVIClass ivi = new IVIClass();
public A(string address)
{
ivi.Initialize(address);
}
public void SendCommand(string cmd)
{
ivi.Send(cmd);
}
}
如何使用:
class Main()
{
A a = new A("1111");//initialize ivi with "1111"
A b = new A("2222");//initialize ivi with "2222"
a.SendCommand("commands");
b.SendCommand("commands");
}
答案 1 :(得分:1)
您需要一个基本接口,我们称之为ICommandSender
,并使用一个扩展方法,将ICommandSender实例作为其来源。
// Base interface
public interface ICommandSender
{
// Shared definition
IVIClass ivi;
}
public class A : SomeOtherClass, ICommandSender
{
// A code here
}
public class B : SomeOtherClass, ICommandSender
{
// B code here
}
// Extension Methods are held in a static class (think Façade Pattern)
public static class ExtMethods
{
// Accept the source and cmd
// The this keyword indicates the target type.
public static void SendCommand(this ICommandSender source, string cmd)
{
source.ivi.Send(cmd);
}
}
// Main doesn't change at all.
class Main()
{
//I want my main to keep this format
A a = new A();
B b = new B();
a.SendCommand("commands");
b.SendCommand("commands");
}
答案 2 :(得分:0)
介绍一个基类?
class BaseClass
{
IVIClass ivi = new IVIClass();
public void SendCommand(string cmd)
{
ivi.Send(cmd);
}
}
class A : BaseClass
{
public A()
{
string address = "1111";
ivi.Initialize(address);
}
}
class B : BaseClass
{
public B()
{
string address = "2222";
ivi.Initialize(address);
}
}
答案 3 :(得分:0)
abstract class AbstractClass{
protected String socket;
public AbstractClass(String socket){
this.socket = socket;
}
public virtual void SendCommand(String cmd){
//dostuff
}
}
class A : AbstractClass{
public A(String socket):base(socket){
}
//you can ovverride the virtual method if need be.
}
B类相同。