相关疑难解决方法(0)

扩展方法冲突

假设我在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;
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

例如,这些方法实际上并没有做任何事情.

现在让我们考虑一下这段代码:

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 ?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:

我知道只会选择一种扩展方法.
会是哪一个?为什么? …

c# methods extension-methods conflict namespaces

38
推荐指数
3
解决办法
8665
查看次数

标签 统计

c# ×1

conflict ×1

extension-methods ×1

methods ×1

namespaces ×1