从实现者调用接口扩展方法在C#中很奇怪
发布时间:2020-12-15 08:41:45 所属栏目:百科 来源:网络整理
导读:调用在实现者的接口上工作的扩展方法似乎需要使用this关键字.这看起来很奇怪. 有谁知道为什么? 有没有更简单的方法来获得接口的共享实现? 当我遭受多重继承/混合撤销时,这让我感到烦恼. 玩具示例: public interface ITest{ Liststring TestList { get; }}
调用在实现者的接口上工作的扩展方法似乎需要使用this关键字.这看起来很奇怪.
有谁知道为什么? 有没有更简单的方法来获得接口的共享实现? 当我遭受多重继承/混合撤销时,这让我感到烦恼. 玩具示例: 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)是:它是:
>减少搜索空间/复杂性 – 即不必考虑所有可用的扩展方法(并修剪它们),除非首先有表达式. 就个人而言,我希望它能够始终如一地工作 – 第一个似乎不是一个大问题(但后来,我不编写编译器),也没有接近通常这个.*是可选的事实(可能有影响,如当地的代码风格指导,即“你应该使用它.”). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |