所有的接口都是......以最简单的形式......是一个类的实现。接口提供的一大好处(对我来说)是解耦你的代码......本质上它使你的代码更少依赖于其他类。
示例情况。
假设您有 3 种不同的货币,美元、印度卢比和欧元。如果没有接口,您将拥有此代码。
UsDollar currency1 = new UsDollar();
使用相应的类。如果您想将 UsDollar 换成卢比,则必须换出代码/进行任何必要的更改以支持下一个课程
Rupee currency1 = new Rupee();
但是通过使用接口,您可以解耦对正在使用的特定类的依赖,并改用接口(类似于您发布的示例 sn-p)。
假设你有一个实现 CurrencyValue 整数和 Exchange Rate 方法的接口
public interface ICurrency
{
int CurrencyValue { get; set; }
void ExchangeRate(double percent);
}
然后您将拥有以下 3 个从接口继承的类。请记住,如果一个类继承自该接口,则它们必须实现与该接口实现的相同。
public class UsDollar : ICurrency
{
public int CurrencyValue { get; set; }
public void ExchangeRate(double percent)
{
Console.WriteLine("Your Exchange Rate for Us Dollar is {0}", CurrencyValue * percent);
}
}
public class Euro : ICurrency
{
public int CurrencyValue { get; set; }
public void ExchangeRate(double percent)
{
Console.WriteLine("Your Exchange Rate for Euro is {0}", CurrencyValue * percent);
}
}
public class Rupee : ICurrency
{
public int CurrencyValue { get; set; }
public void ExchangeRate(double percent)
{
Console.WriteLine("Your Exchange Rate for Rupee is {0}", CurrencyValue * percent);
}
}
所以通过改变你的用法
Rupee currency1 = new Rupee();
到
ICurrency currency1 = new Rupee();
您使用此类的代码不再关心它是卢比、美元、欧元……还是您最终创建的任何其他货币类别。
接口也可以在各种设计模式中提供价值(因素模式)。
示例用法:
ICurrency currency1 = new UsDollar();
ICurrency currency2 = new Euro();
ICurrency currency3 = new Rupee();
currency1.CurrencyValue = 10;
currency2.CurrencyValue = 13;
currency3.CurrencyValue = 16;
currency1.ExchangeRate(1.1);
currency2.ExchangeRate(1.6);
currency3.ExchangeRate(1.5);
所以回答你的问题
IModelDoc2 swModel; //IModelDoc2 is an interface. What are we doing here?
这应该专门创建某个类类型的新对象(在我的示例中,这与 ICurrency currency1 = new UsDollar(); 相同)。因此,在您的代码中的某处,您可以将值分配给 swModel,该值将是从 IModelDoc2 继承的某个类/类型。
希望这对您有所帮助/澄清。
但要阅读接口,我建议使用链接:
http://msdn.microsoft.com/en-us/library/87d83y5b%28v=vs.80%29.aspx