我想我记得很久以前读过,在 C#3 中,扩展方法只能应用于基本类型和接口(interface);并且在 C#4 中,它们可用于扩展任何类型。这与我现在看到的不相符,我发现很难找到它的记录。
这是真的还是我的内存造成的?
关于哪些类型可以扩展的规则是什么?
C# 3 和 4 之间有什么区别吗?
最佳答案
Is there any truth to this?
没有。
What are the rules relating to which types can be extended?
调用规则在 C# 4 规范的第 7.6.5.2 节中。声明规则在第 10.6.9 节。
回答您的具体问题:非托管指针类型可能无法扩展。
Are there any differences between C# 3 and 4?
是的。 C# 4 添加了处理“动态”的额外规则。扩展方法不动态解析;如果你有
dynamic d = 10;
d.MyIntExtension();
那么动态语言运行时将不会在 int 上找到扩展方法。见
Will the dynamic keyword in C#4 support extension methods?
了解更多详情。
关于c# - C#3 和 4 中扩展方法的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4593230/