【问题标题】:How can I use an extension method without importing the whole namespace? [duplicate]如何在不导入整个命名空间的情况下使用扩展方法? [复制]
【发布时间】:2021-11-06 05:43:22
【问题描述】:

我将Google.Api.CommonProtos NuGet 包与我的C# 服务一起使用,并希望将Google.Type.Date 类型与System.DateTime 类型一起使用。我还想使用包含的扩展方法在System.DateTimeGoogle.Type.Date 之间来回转换。

问题是,当我导入扩展方法.ToDate() 时,它会引入整个Google.Type 命名空间,这会导致DateTimeSystem.DateTimeGoogle.Type.DateTime 之间产生歧义。此代码未构建:

using System;
using Google.Type;

namespace Example
{
    public class ExampleClass
    {
        public Google.Type.Date TomorrowDate(DateTime date) => date.AddDays(1).ToDate();
    }
}
// Error    CS0104  'DateTime' is an ambiguous reference between 'Google.Type.DateTime' and 'System.DateTime'

我可以在引用 Google.Type.DateTime 时保持冗长,但我不想开始在我们的应用程序中重写 DateTime 的所有用法来说 System.DateTime。我怎样才能做到这一点?实际上,如何在不导入(C# 中的using)声明扩展方法的整个命名空间的情况下使用特定类中定义的扩展方法?

【问题讨论】:

    标签: c# datetime static namespaces extension-methods


    【解决方案1】:

    C# 可以静态使用类来允许访问静态定义的方法;扩展方法是静态的。在上面的示例中,.ToDate() 扩展方法定义在 Google.Type.DateExtensions 类中(在 Google.Type 命名空间中),因此可以静态使用 仅该类 来访问其扩展方法,而不是导入整个 Google.Type 命名空间。

    此代码有效:

    using System;
    using static Google.Type.DateExtensions;
    
    namespace Example
    {
        public class ExampleClass
        {
            public Google.Type.Date TomorrowDate(DateTime date) => date.AddDays(1).ToDate();
        }
    }
    

    原答案:https://github.com/googleapis/gax-dotnet/issues/418

    【讨论】:

      猜你喜欢
      • 2016-03-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      相关资源
      最近更新 更多