为什么我必须编写命名空间来访问此扩展方法?

Álv*_*cía 0 c# extension-methods

我有一个项目,有类实现某种类型的扩展方法.例如,我有这个类用于ObservableCollection:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections.ObjectModel;


namespace MyProject.Collections.Utils
{
    public static class ObservableCollection
    {
        public static void RemoveAll<T>(this ObservableCollection<T> collection, Func<T, bool> condition)
        {
            for (int i = collection.Count - 1; i >= 0; i--)
            {
                if (condition(collection[i]))
                {
                    collection.RemoveAt(i);
                }
            }
        }//RemoveAll
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个类,在我的主项目中我可以使用这个库和使用:

using MyProject.Collections.Utils
Run Code Online (Sandbox Code Playgroud)

当我想使用扩展方法时,我可以这样做:

ObservableCollection<MyType> myOC = new ObservableCollection<MyType>();
myOC.RemoveAll(x=>x.MyProperty == "123");
Run Code Online (Sandbox Code Playgroud)

所以我可以访问我的扩展方法.

但是,我有另一个Decimal类,是这样的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace MyProject.Decimal.Utils
{
    public static class Decimal
    {
        public static decimal? Parse(this string paramString)
        {
            try
            {
                myCode
            }
            catch
            {
                throw;
            }
        }//Parse
    }
}
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,虽然在我的主要项目中导入了类:

using MyProject.Decimal.Utils;
Run Code Online (Sandbox Code Playgroud)

如果我这样做:

decimal? myDecimalParsed= Decimal.Utils.Decimal.Parse("123");
Run Code Online (Sandbox Code Playgroud)

为什么在这种情况下我不能这样做?:

decimal? myDecimalParsed= decimal.Parse("123");
Run Code Online (Sandbox Code Playgroud)

非常感谢.

Jon*_*eet 7

两个问题:

  • 您不能使用扩展方法,就好像它们是扩展类型的静态方法一样
  • System.Decimal已经有了一个Parse方法,编译器总是在扩展方法之前查找"真实"方法.

实际上,你可以

decimal? miTiempoEstimadoParseado = decimal.Parse("123");
Run Code Online (Sandbox Code Playgroud)

...但是这只会调用普通方法,然后decimaldecimal?正常方式隐式转换为.

请注意,目前你还没有真正使用你的方法作为扩展方法 - 这样做你会写下这样的东西:

decimal? miTiempoEstimadoParseado = "123".Parse();
Run Code Online (Sandbox Code Playgroud)

...但我个人认为这非常丑陋,部分原因是方法名称根本没有指明目标类型,部分原因是因为通过约定Parse方法抛出异常而不是在失败时返回空值.你可能想要一个不同的名字.