C# 扩展方法和新发布的扩展程序集
如何评估扩展方法?或者在一个非常特定的用例中:如果一个扩展方法被程序集的新版本实现为类实例方法,并且该程序集已更新,但依赖程序集未更新,那么它们是否会:C# 扩展方法和新发布的扩展程序集,c#,extension-methods,C#,Extension Methods,如何评估扩展方法?或者在一个非常特定的用例中:如果一个扩展方法被程序集的新版本实现为类实例方法,并且该程序集已更新,但依赖程序集未更新,那么它们是否会: 仍然访问扩展方法 访问新的类实例方法 扔 我添加了以下几个简单的代码示例:FooExtensions程序集、IFoo程序集、FooBefore程序集、FooAfter程序集和测试程序集。其思想是,第一个版本从FooExtensions、IFoo、FooBefore和Test开始。该测试将动态加载程序集Foo和依赖程序集,并创建一个Foo。然后,
#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
扩展方法只是常规静态方法的语法糖,因此它们将像以前一样工作,直到重新编译依赖程序集,此时编译器将找到新的实例方法并生成对它的调用