Cでの拡張メソッドを作成する方法


拡張メソッドは、新しい派生型を作成するか、元の型を変更することなく、任意のC Count型に追加機能を追加するメソッドです.

拡張メソッドの形式
public static class NameOfTheClass
{
    public static ReturnType(this typeOfTheSource source)
    {
        // Extension method definition
    }
}

拡張メソッド
. NET指定した文字列が空の文字列であるかどうかを示す静的メソッドを提供します.この機能性を取ることができ、カスタム拡張メソッドでそれをラップできます.
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string source)
    {
        return string.IsNullOrEmpty(source);
    }
}

用途
string str = "just a string";
if (str.IsNullOrEmpty)
{
    // do something if the string is null or empty
}

例:追加パラメータを含む拡張メソッド
次の例では、追加のパラメーターを使用して拡張メソッドを生成する方法を説明します.Bellowメソッドは与えられた小数点を与えられた小数点に丸めます.
public static class DecimalExtensions
{
    public static decimal Rounding(this decimal dec, int precision)
    {
        return Math.Round(dec, precision);
    }
}

例:汎用拡張メソッド
次の拡張メソッドは、パラメーターとソースとしてジェネリック値型をとります.指定した配列にある値が存在するかどうかを調べます.
public static class StructExtensions
{
    public static bool In<T>(this T value, params T[] parms) where T : struct
        => parms.Any(x => x.Equals(value));
}
あなたがより多くの物語を読みたいならば、kapadev blogをチェックしてください