如果某些方法我在多个类里面都会通用,我们一般有几种方法可以实现?
我们常想到的方法有
1.写一个静态类,在其他类里面直接调用,例如:
using System;
// 静态类
public static class StaticExample
{
// 静态方法
public static void PrintMessage(string message)
{
Console.WriteLine(message);
}
}
// 其他类
public class AnotherClass
{
public void CallStaticMethod()
{
// 直接调用静态类的方法
StaticExample.PrintMessage("Hello from AnotherClass");
}
}
class Program
{
static void Main()
{
// 在主程序中调用静态类的方法
StaticExample.PrintMessage("Hello from Main");
// 创建另一个类的实例并调用其中的方法
AnotherClass anotherObject = new AnotherClass();
anotherObject.CallStaticMethod();
}
}
2.写一个父类,子类继承实现,例如:
public class BaseClass
{
public void CommonMethod()
{
// 具体实现
}
}
public class DerivedClass1 : BaseClass
{
// 可以直接使用 CommonMethod
}
public class DerivedClass2 : BaseClass
{
// 可以直接使用 CommonMethod
}
3.是我要说的一种更方便的方式,定义一个接口,包含通用方法的实现,然后让多个类调用接口。
public interface ICommonInterface
{
void CommonMethod();
}
public class Class2 : ICommonInterface
{
public ICommonInterface CommonInterface=> this;
public void Test()
{
CommonInterface.CommonMethod();
}
}