【发布时间】:2011-03-08 04:38:18
【问题描述】:
我在另一个线程中进行了讨论,发现类方法优先于具有相同名称和参数的扩展方法。这很好,因为扩展方法不会劫持方法,但假设您已将一些扩展方法添加到第三方库:
public class ThirdParty
{
}
public static class ThirdPartyExtensions
{
public static void MyMethod(this ThirdParty test)
{
Console.WriteLine("My extension method");
}
}
按预期工作:ThirdParty.MyMethod ->“我的扩展方法”
但随后第三方更新了它的库并添加了一个与您的扩展方法完全相同的方法:
public class ThirdParty
{
public void MyMethod()
{
Console.WriteLine("Third party method");
}
}
public static class ThirdPartyExtensions
{
public static void MyMethod(this ThirdParty test)
{
Console.WriteLine("My extension method");
}
}
ThirdPart.MyMethod -> “第三方方法”
现在,由于第三方方法“劫持”了您的扩展方法,突然代码在运行时的行为会有所不同!编译器不会给出任何警告。
有没有办法启用此类警告或以其他方式避免这种情况?
【问题讨论】:
标签: c# extension-methods