使用扩展方法需要注意的几点:
- The method is define in a top level static class ( the class is directly under the namespace)
- The method is static and decorates its first param with a new param modifier this, this param is called the "instance parameter" and its an error to use the "this" modifiers on any other parameter.
- No other parameter modifiers ( ref, out etc) are allowed with "this" (so values types can't be passed by reference to an extension methods, VB will allow ref).
- The instance parameter can't be a pointer type.
- The method is public (its accessible to anyone who can get to its parentclass).
- The Type parameter used must be defined on the method and not the parentclass.
- The instance parameter cannot have the type of the Type parameter.
Sample:
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
6
namespace NewFeatures
7
2
3
4
5
6
7
参阅 :Sree's ventures Extension method in C#