LoginSignup
0
0

More than 1 year has passed since last update.

C# 拡張メソッド(メソッドチェーン)

Posted at
/// <summary>
/// 文字列を数字に変換する
/// 文字列に数字以外が入っていたら null を返す
/// </summary>
/// <param name="message">数字の文字列</param>
/// <returns>文字列が数字であればその値を int で返す そうでなければ null を返す</returns>
public static int? ToInt(this string message)
{
    return int.TryParse(message, out var result) ? result : null;
}
//------別のScript
void Start(){
    string message = "123456";
    var num1 = message.ToInt();
    Debug.Log(num1);//123456
    message = "1234a";
    var num2 = message.ToInt();
    Debug.Log(num2);//null
}
public static int? ToInt(this string message)

引数でthisをつけることで拡張メソッドとして扱うことができる

/// <summary>
/// int型の数値にint型の引数を掛けた値をセットする
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public static void Mul(this ref int x,int y)
{
    x = x * y;
}
//------別のScript
void Start(){
    int i = 2;
    i.Mul(4);
    Debug.Log(i);//8
}
public static void Mul(this ref int x,int y)

引数を2つ以上つけることもできる

拡張メソッド

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0