扩展方法冲突 [英] Extension methods conflict

查看:132
本文介绍了扩展方法冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有2扩展方法的字符串,在2个不同的命名空间:

Lets say I have 2 extension methods to string, in 2 different namespaces:

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;
        }
    } 
}



这些方法只是举例,他们没有做任何事情。

These methods are just for example, they don't really do anything.

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

Now lets consider this piece of code:

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 ?
        }
    }
}



问题

我知道,只有延长的方法之一将选择结果
会是哪一个?为什么?

I know that only one of the extension methods will be chosen.
Which one will it be ? and why ?

编辑:

这也困扰我,但没有那么多,因为它是在静态类的静态方法毕竟:

This also bothers me, but not as much because it's a static method in a static class after all:

我如何可以选择从某一个命名空间一定的方法结果
我通常会使用 Namespace.ClassNAME.Method() ...但是,这只是跳动的扩展方法的整体思路。而且我不认为你可以使用 Variable.Namespace.Method()

How can I choose a certain method from a certain namespace ?
Usually I'd use Namespace.ClassNAME.Method() ... But that just beats the whole idea of extension methods. And I don't think you can use Variable.Namespace.Method()

推荐答案

没有方法可以选择:电话是模糊的,并不会编译

No method will be chosen: the call is ambiguous and will not compile.

为什么不能这样做 Namespace.ClassNAME。方法()?当然,没有什么可以阻止你对待扩展方法作为普通静态方法,而事实上,这是为你解决模糊并有计划编译的唯一方法。

Why can't you do Namespace.ClassNAME.Method()? Certainly there is nothing that prevents you from treating extension methods as normal static methods, and in fact this is the only way for you to fix the ambiguity and have the program compile.

这篇关于扩展方法冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆