13,230
回編集
(→整数型) |
|||
| 61行目: | 61行目: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<br> | <br> | ||
==== 浮動小数点型 ==== | |||
以下の例では、拡張メソッドAddは、浮動小数点型を拡張している。(第1引数のthis double)<br> | |||
拡張メソッドに第2引数を指定する時、拡張メソッドの第1引数として渡される。<br> | |||
<br> | |||
つまり、拡張メソッドに引数を付加して呼び出す場合、その引数は拡張メソッドの第2引数以降として渡される。<br> | |||
<br> | |||
<syntaxhighlight lang="c#"> | |||
using System; | |||
namespace FloatingPointExtensions | |||
{ | |||
public static class FloatingPointExtension | |||
{ | |||
public static double Add(this double m, double n) => m + n; | |||
public static float Add(this float m, float n) => m + n; | |||
// オーバーロードを追加して、int型の引数も受け付ける場合 | |||
public static double Add(this double m, int n) => m + n; | |||
public static float Add(this float m, int n) => m + n; | |||
// ジェネリックを使用して型パラメータを導入する場合 | |||
// これにより、様々な数値型に対応する | |||
public static T Add<T, U>(this T m, U n) where T : struct, IConvertible | |||
where U : struct, IConvertible | |||
{ | |||
dynamic a = m; | |||
dynamic b = n; | |||
return a + b; | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
==== 文字列型 ==== | ==== 文字列型 ==== | ||
以下の例では、CustomExtensions名前空間のStringExtensionクラスを作成して、WordCount拡張メソッドを実装している。<br> | 以下の例では、CustomExtensions名前空間のStringExtensionクラスを作成して、WordCount拡張メソッドを実装している。<br> | ||