【发布时间】:2011-07-14 02:31:21
【问题描述】:
假设我有 2 个字符串扩展方法,位于 2 个不同的命名空间中:
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() -
我不知道,但我认为这不应该真的发生......在类中给方法一个更具描述性的名称,而不是试图强制编译器自动选择一个。我有兴趣查看回复。
-
我不会说我会那样做。但是假设您正在使用某个库,并且在不知不觉中,那里有一个同名的扩展方法....只是想知道它是如何选择的
-
我认为这是一个很好的问题 - 不管其他建议如何,知道这一点会很高兴。
-
test1.MyExtensions.TestMethod(a)超越了扩展方法的想法。我已经编辑了我的问题,这并不是真正困扰我的问题。
标签: c# methods namespaces extension-methods conflict