假设我有两个字符串的扩展方法,在两个不同的命名空间中:
namespace test1
{
public static class MyExtensions
{
public static int TestMethod(this String str)
{
return 1;
}
}
}
namespace test2
{
public static class MyExtensions2
{
public static int TestMethod(this String str)
{
return 2;
}
}
}
这些方法仅为示例,它们并没有实际作用。
现在让我们考虑这段代码:
using System;
using test1;
using test2;
namespace blah {
public static class Blah {
public Blah() {
string a = "test";
int i = a.TestMethod(); //Which one is chosen ?
}
}
}
问题:
我知道只有一个扩展方法会被选择。
它将是哪一个?为什么?
编辑:
这也让我困扰,但毕竟这是静态类中的静态方法:
如何从特定命名空间中选择某个方法?
通常我会使用Namespace.ClassNAME.Method()
... 但那样就打败了扩展方法的初衷。而且我不认为你可以使用Variable.Namespace.Method()
test1.MyExtensions.TestMethod(a)
而不是a.TestMethod()
。请注意,这并不是对原代码的修改,而是提供了一个备选方案。 - k3btest1.MyExtensions.TestMethod(a)
打破了扩展方法的思想。我已经编辑了我的问题,那不是真正困扰我的事情。 - Yochai Timmerusing static
来指定您想要使用的扩展类 - https://riptutorial.com/csharp/example/34/explicitly-using-an-extension-method - ProfNandaa