Differences between extension methods in C#3 & 4
I think I remember reading a long time ago that in C#3 extension methods could only be applie开发者_如何学Pythond to primitive types and interfaces; and that in C#4 they could be used to extend any type. This doesn't seam to match up with what I am seeing now and I am finding it difficult to find this documented.
Is there any truth to this or did my memory make it all up?
What are the rules relating to which types can be extended?
Are there any differences between C# 3 and 4?
Is there any truth to this?
No.
What are the rules relating to which types can be extended?
The rules for invocations are in section 7.6.5.2 of the C# 4 specification. The rules for declarations are in section 10.6.9.
To answer your specific question: unmanaged pointer types may not be extended.
Are there any differences between C# 3 and 4?
Yes. C# 4 adds additional rules for dealing with "dynamic". Extension methods are not resolved dynamically; if you have
dynamic d = 10;
d.MyIntExtension();
then the dynamic language runtime will not find the extension method on int. See
Will the dynamic keyword in C#4 support extension methods?
for more details.
You made it up! As far as I'm aware there have been no changes to the rules between C#3 and C#4.
(And a cursory comparison of the relevant spec documents seems to confirm this.)
Is there any truth to this or did my memory make it all up?
You made it up. Extensions methods have always been used on IEnumerable<T>
.
Edit:
Here is the MSDN Link for Fx3.5 (C# 3) where the 2nd example is an extension for System.String, and String is not a primitive type.
精彩评论