我如何使用扩展将接口一致性添加到我无法控制的类型?

How can I use an extension to add interface conformance to a type that is outside my control?

在 Beef 文档的 extensions page 上,它是这样说的:

Extensions can be useful for adding interface conformance to types that are outside your control (ie: system types or types defined in another library).

遗憾的是,它没有提供该用例的示例,我不知道如何继续。

假设我有一个接口IFooBarable:

interface IFooBarable
{
    void FooBar();
} 

并且我想将这个扩展方法添加到系统库类型System.DateTime:

namespace System
{
    extension DateTime
    {
        public void FooBar()
        {
            String s = scope .();
            ToLongTimeString(s);

            Console.WriteLine("This dateTime ({}) has FooBarred", s); 
        }
    }
}

... 这样 DateTime 就可以实现 IFooBarable.

是否应该有一种方法可以告诉编译器将 DateTime 视为 IFooBarable 的实现?例如,这样编译:

using System;

interface IFooBarable
{
    void FooBar();
}

/* extension code here */

namespace Program
{
    public class Program
    {
        static void Main()
        {
            IFooBarable t = DateTime.Now;

            t.FooBar();
        }
    }
}

事实证明,使用与 class 声明中指示实现相同的语法一样简单。也就是说,上面你只需要使用 extension DateTime : IFooBarable:

using System;

interface IFooBarable
{
    void FooBar();
}

namespace System
{
    extension DateTime : IFooBarable
    {
        public void FooBar()
        {
            String s = scope .();
            ToLongTimeString(s);

            Console.WriteLine("This dateTime ({}) has FooBarred", s); 
        }
    }
}

namespace Program
{
    public class Program
    {
        static void Main()
        {
            IFooBarable t = DateTime.Now;

            t.FooBar();
        }
    }
}

您甚至可以通过在 extension:[=14= 中不包含任何内容来注册 class 已经具有的同名接口方法的实现方法]

using System;

interface IFooBarable
{
    void ToLongTimeString();
}

namespace System
{
    extension DateTime : IFooBarable
    {
    }
}

namespace Program
{
    public class Program
    {
        static void Main()
        {
            IFooBarable t = DateTime.Now;

            String s = scope .(); 
            t.ToLongTimeString(s);

            Console.WriteLine("{}", s);
        }
    }
}