擴充套件方法與介面相結合
使用帶介面的擴充套件方法非常方便,因為實現可以儲存在類之外,並且向類新增一些功能所需要的是用介面來裝飾類。
public interface IInterface
{
string Do()
}
public static class ExtensionMethods{
public static string DoWith(this IInterface obj){
//does something with IInterface instance
}
}
public class Classy : IInterface
{
// this is a wrapper method; you could also call DoWith() on a Classy instance directly,
// provided you import the namespace containing the extension method
public Do(){
return this.DoWith();
}
}
使用像:
var classy = new Classy();
classy.Do(); // will call the extension
classy.DoWith(); // Classy implements IInterface so it can also be called this way