c# - 从实现者调用接口(interface)扩展方法在 C# 中很奇怪

标签 c# extension-methods multiple-inheritance mixins

从实现者调用在接口(interface)上工作的扩展方法似乎需要使用 this 关键字。这似乎很奇怪。

有人知道为什么吗?

是否有更简单的方法来获取接口(interface)的共享实现?

这让我很恼火,因为我正在遭受多重继承/mixin 撤销。

玩具示例:

public interface ITest
{
    List<string> TestList { get; }
}

public static class TestExtensions
{
    private const string Old = "Old";
    private const string New = "New";

    public static void ManipulateTestList(this ITest test)
    {
        for (int i = 0; i < test.TestList.Count; i++)
        {
            test.TestList[i] = test.TestList[i].Replace(Old, New);
        }
    }
}

public class Tester : ITest
{
    private List<string> testList = new List<string>();
    public List<string> TestList
    {
        get { return testList; }
    }

    public Tester()
    {
        testList.Add("OldOne");
        testList.Add("OldTwo");

        // Doesn't work
        // ManipulateTestList();

        // Works
        this.ManipulateTestList();
    } 
}

最佳答案

我直接向语言团队询问了这个确切的问题。我手边没有电子邮件,但基本上答案(来自 Mads,IIRC)是:

  • 减少搜索空间/复杂性 - 即不必考虑所有可用的扩展方法(并修剪它们),除非首先有表达式。
  • 减少扩展方法意外“接管”常规方法(即更匹配)的可能性

就我个人而言,我希望它能够始终如一地工作 - 第一个似乎不是什么大问题(但后来,我不编写编译器),两者 都无法解决通常情况下的问题this.* 是一个可选的东西(可能会影响本地代码风格指南,即“你应该使用 this.”)。

关于c# - 从实现者调用接口(interface)扩展方法在 C# 中很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3715161/

相关文章:

c# - .NET DateTime 不在 ToShortTimeString() 中返回 AM/PM

c# - 使用 Output0Buffer 类时出现 SSIS 脚本转换错误

c# - 使用 PostMessage 发送正确的 ALT+C

python - 在 Python 中调用所有 __init__ 但一次

java - 如何制作一个实现一个接口(interface)和两个泛型类型的 Java 类?

Python装饰一个类改变父对象类型

c# - 在使用 Rx 的最后一个值的指定增量之后,如何让位置更新通过?

c# - 如何使用扩展方法加入 .NET Entity Framework 中的多个列?

c# - 为什么我的程序不能确定对动态变量使用哪种扩展方法?

c# - 识别扩展方法的反射(reflection)