C Sharpの基礎 - 拡張メソッド
ナビゲーションに移動
検索に移動
概要
C#において、独自の拡張メソッドを実装する手順を記載する。
拡張メソッドを使用するには、usingディレクティブを使用して、拡張メソッドが定義されている名前空間を指定する。
拡張メソッドの実装
- 拡張メソッドを実装するための静的クラスを定義する。
この静的クラスは、クライアントコードから参照できる必要がある。 - 拡張メソッドを静的メソッドとして実装する。
- メソッドの最初の引数では、操作する型を指定する。
型名の前には、this修飾子を付加する。
名前の衝突において、呼び出し元のクラスで定義されているメソッドが優先されるため、拡張メソッドが使用されることはない。
拡張メソッドの使用
- 呼び出し元において、usingディレクティブを使用して、拡張メソッドの静的クラスを含む名前空間を指定する。
- クラスのインスタンスメソッドと同様にメソッドを記述する。
呼び出し元では、最初の引数は指定しない。
これは、演算子を適用する型を表すものであり、コンパイラはオブジェクトの型を既に認識しているためである。
指定する必要があるのは、第2引数以降の引数のみである。
以下の例では、CustomExtensions名前空間のStringExtensionクラスを作成して、WordCount拡張メソッドを実装している。
この拡張メソッドは、第1引数で指定したStringクラスを操作する。
using System.Linq;
using System.Text;
using System;
namespace CustomExtensions
{
// Extension methods must be defined in a static class.
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
// Import the extension method namespace.
using CustomExtensions;
namespace Extension_Methods_Simple
{
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}