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

本文关键字:扩展 程序集 方法 新发布 | 更新日期: 2023-09-27 18:09:08

如何评估扩展方法?或者在一个非常具体的用例中:如果一个扩展方法被一个程序集的新版本实现为一个类实例方法,并且该程序集更新了,但依赖的程序集没有更新,它们会:

  1. 仍然访问扩展方法
  2. 访问新的类实例方法

我添加了以下简单的代码示例:一个FooExtensions程序集,一个IFoo程序集,一个FooBefore程序集和一个FooAfter程序集,以及一个Test程序集。我们的想法是,第一个版本从FooExtensions、IFoo、FooBefore和Test开始。该测试将动态加载程序集FooBefore和相关程序集,并创建一个Foo。然后它将调用GetMessage并写入控制台"message"。对于第二个版本,我们只将FooBefore替换为FooAfter,并再次运行测试。然后会发生什么?

#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

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

扩展方法只是常规静态方法的语法糖,因此它们将像以前一样工作,直到您重新编译相关程序集,此时编译器将找到新的实例方法并生成对它的调用。