在两个类C#之间共享一个方法
本文关键字:共享 一个 方法 之间 两个 | 更新日期: 2023-09-27 18:26:54
我已经将我所拥有的简化为:
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。
如何合并它们?
如果这是您的实际场景,则不需要两个只能处理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");
}
您需要一个基本接口,让我们称之为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");
}
引入基类?
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);
}
}
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类相同。