实现扩展方法接口 C#
本文关键字:接口 方法 扩展 实现 | 更新日期: 2023-09-27 18:37:08
我是 C# 的新手,在理解如何实现接口的扩展方法方面有问题。我没有找到有关此问题的任何材料。从我找到的有关 C# 中常规扩展方法的材料中,我期望以下简单的演示示例工作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testExtension
{
public interface IcheckThingsOut
{
bool x();
}
public static class extensionInterface
{
public static bool y(this IcheckThingsOut bla) { return true;}
}
public class implementInteface : IcheckThingsOut
{
bool IcheckThingsOut.x()
{
return true;
}
bool IcheckThingsOut.y()
{
return false;
}
}
}
但是编译器仍然不满意。我错过了什么,这里的正确语法是什么(具有与代码相同的语义)?
你搞砸了扩展方法和接口的概念。扩展方法只是在静态类上调用静态方法的编译器便捷方法。它们不扩展接口。编译器在使用扩展方法时的作用是:
IcheckThingsOut instance = new IcheckThingsOutImpl();
instance.y();
。将转换为:
IcheckThingsOut instance = new IcheckThingsOutImpl();
extensionInterface(instance, y);
如您所见,y 不是接口上的方法。这就是为什么您无法在实现中显式实现它的原因。
您似乎希望使用的是"扩展方法"。为此目的,您的 extensionInterface
类已正确实现。
但是,创建扩展方法实际上并不会扩展接口,因此尽管可以调用 myIcheckThingsOut.y()
,但不能在隐式或显式实现IcheckThingsOut
的类中重新实现该方法。
不能在"扩展"类或接口中更改扩展方法的实现。扩展方法是实现。
扩展方法提供了一种将方法"添加"到接口或类的方法。整个想法是,您正在扩展的接口或类并不"知道"这些方法。换句话说,您可以在不更改类或接口本身的情况下"添加"功能。
(请注意,虽然表示法表明您正在向接口添加方法,但实际上就运行时而言,这些方法是纯静态方法)。
bool IcheckThingsOut.y()
{
return false;
}
是错误的:IcheckThingsOut没有提供函数y
的原型。它应该只是
bool y()
{
return false;
}
因为它只是隐藏了另一种方法
IcheckThingsOut 没有 bool y()