C#拓展方法
阿新 • • 發佈:2022-03-31
一、定義介面
public interface ICalculate
{
int Add(int a, int b);
}
二、定義實現介面類
public class A : ICalculate
{
public int Add(int a, int b)
{
return a + b;
}
}
三、介面拓展
定義靜態方法和靜態類,把介面當做引數傳入到方法體
public static class InterfaceExtend { public static int Sub( this ICalculate calculate, int a,int b) { return a - b; } public static int Maltiply(this ICalculate calculate, int a, int b) { return a * b; } public static int Division(this ICalculate calculate, int a, int b) { return a / b; } }
四、呼叫測試
A a = new A();
int res = a.Maltiply(2, 3);
Console.WriteLine(res);
res = a.Division(10, 2);
Console.WriteLine(res);
res = a.Sub(100,1);
Console.WriteLine(res);