从实现者调用在接口(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/