我读了一些关于接口的文章,但对我来说还不够清楚.请帮助找到使用接口的正确方法.我的问题在codeample的评论中:
using System;
namespace IfTest
{
public interface ICalculator
{
void Sum(int a, int b);
}
public class MyCalc : ICalculator
{
public void Sum(int a, int b)
{
Console.WriteLine(a + b);
}
}
class Program
{
static void Main(string[] args)
{
//What's the difference between
ICalculator mycalc;
mycalc = new MyCalc();
mycalc.Sum(5, 5);
//and this. When should we use this way?
MyCalc mc = new MyCalc();
mc.Sum(5, 5);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在ICalculator mycalc
声明类型变量时ICalculator
,在编译时,您只能调用属于此接口的方法.您将无法调用不属于接口但仅属于实现类的方法.
在MyCalc mc
声明类型变量时MyCalc
,在编译时,您只能调用此类及其继承的接口上的所有方法.
在运行时,两者之间根本没有区别.
对接口进行编程时,建议使用对象层次结构中最抽象的可能类型.所以在这种情况下,这将是ICalculator
界面.
这允许在调用代码和实际实现之间更好地分离.如果调用代码是针对接口编程的,则它不再与MyCalc
可以与其他实现交换的特定实现相关联.