gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:52 32 4
gpt4 key购买 nike

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

  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

最佳答案

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

关于c# - 扩展方法和新发布的扩展程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7499026/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com