扩展方法和新发布的扩展程序集

问题描述:

如何评估扩展方法?或在一个非常具体的用例:如果扩展方法是通过组件的新版本的类的实例方法来实现和组件更新,但依赖程序都没有,他们会:扩展方法和新发布的扩展程序集

  1. 仍接入分机方法
  2. 进入新的类实例方法

我添加了一个FooExtensions组件,IFoo的组件,FooBefore组件和组装FooAfter的下面简单的代码样本和测试组件。这个想法是第一个版本从FooExtensions,IFoo,FooBefore和Test开始。测试将动态加载程序集FooBefore和相关程序集并创建Foo。然后它会调用GetMessage并写入控制台的“消息”。对于第二个版本,我们只用FooAfter替换FooBefore并再次运行测试。那么会发生什么?

#region Assembly FooExtensions 
public static class FooExtensions 
{ 
    public static string GetMessage(this IFoo foo) 
    { 
     return foo.Message; 
    } 
} 
#endregion 

#region Assembly IFoo 
public interface IFoo 
{ 
    string Message { get; } 
} 
#endregion 

#region Assembly Foo before update 
namespace FooBefore 
{ 
    public class Foo : IFoo 
    { 
     public string Message 
     { 
      get { return "message"; } 
     } 
    } 
} 
#endregion 

#region Assembly Foo after update 
namespace FooAfter 
{ 
    public class Foo : IFoo 
    { 
     public string GetMessage() { return "bar"; } 

     public string Message 
     { 
      get { return "message"; } 
     } 
    } 
} 
#endregion 

#region Assembly Test 
public class Class1 
{ 
    public void T() 
    { 
     // if extension method is implemented in new version of deriving assembly and 
     // just that assembly is switched but not dependent assemblies, what happens? 

     // before update: extension method, as we know it 
     Console.WriteLine((Activator.CreateInstance("Foo.DLL", "Foo").Unwrap() as IFoo).GetMessage()); 
     // after update: class instance method, but do we know? 
     Console.WriteLine((Activator.CreateInstance("Foo.DLL", "Foo").Unwrap() as IFoo).GetMessage()); 
    } 
} 
#endregion 

扩展方法是常规的静态方法只是语法糖,所以直到你重新编译的依赖程序集,此时编译器会寻找新的实例方法和产生对它的调用,而不是他们的工作如前。