FC2ブログ
    08 «1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.» 10

    ハルシオンシステムの気ままBlog

    株式会社ハルシオンシステムのメンバーが送る、UnityやらJavaやらの技術的話題から、自社開発のアプリの宣伝とかとかのブログです。ほんと気ままにいきたいと思います。更新日は毎週 月 木でっす!

     

    【ハルシオンブログ】ポケガよろしくお願いします!あ、今日はisNullOrEmptyのお話。 

    花粉が舞いまくってますね。
    鼻水ずびずびです。坂内っす。

    ポケットガール~受け継がれし希望~をよろしくお願いします。
    まじでお願いします!
    URL(Android):https://play.google.com/store/apps/details?id=com.halcyon.pocketgirl3
    URL(iOS):https://itunes.apple.com/jp/app/id1539553611


    さてUnityの基礎的な話。
    IsNullOrEmptyって使ってますか?
    stringがNullか空の時にTrueを返す関数です。


    void Start() {
    string strA = null;
    string strB = "";
    string strC = "abc";

    if (string.IsNullOrEmpty(strA)) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(strA);
    }
    if (string.IsNullOrEmpty(strB)) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(strB);
    }
    if (string.IsNullOrEmpty(strC)) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(strC);
    }
    }


    こんなコードを書くと結果はこうなります。

    Nullか空です
    Nullか空です
    abc


    ちゃんとNullでも空文字でも認識してくれてますね。

    stringだけじゃなく、ListでもNullかどうかの判断がしたい!
    って時はこんなクラスを作るといいらしいです。


    using System.Collections.Generic;

    static class CollectionExt {

    public static bool isNullOrEmpty(this ICollection collection) {
    return (collection == null || collection.Count == 0);
    }
    }

    public static string RetString(this ICollection collection) {
    StringBuilder strBuilder = new StringBuilder();
    foreach (T t in collection) {
    strBuilder.Append(t.ToString());
    }
    return strBuilder.ToString();
    }



    クラス名は適当です。

    これを使うコードを先ほどのStartに続けて書いてみます。


    void Start() {
    string strA = null;
    string strB = "";
    string strC = "abc";

    if (string.IsNullOrEmpty(strA)) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(strA);
    }
    if (string.IsNullOrEmpty(strB)) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(strB);
    }
    if (string.IsNullOrEmpty(strC)) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(strC);
    }

    List lstStr1 = new List{"あ", "い", "う", "え"};
    List lstStr2 = null;
    List lstStr3 = new List();

    if (lstStr1.isNullOrEmpty()) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(lstStr1.RetString());
    }
    if (lstStr2.isNullOrEmpty()) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(lstStr2.RetString());
    }
    if (lstStr3.isNullOrEmpty()) {
    Debug.Log("Nullか空です");
    } else {
    Debug.Log(lstStr3.RetString());
    }
    }



    結果はこんな感じ。

    Nullか空です
    Nullか空です
    abc
    あいうえ
    Nullか空です
    Nullか空です

    ちゃんとNullか空か、もしくは中身が入っているのかとれてますね。

    ということで、簡単にですが、isNullOrEmptyの使い方の紹介でした。

    では、あでゅ~ノシ

    Category: 開発日記(Unity)

    tb 0 : cm 0   

    コメント

    コメントの投稿

    Secret

    トラックバック

    トラックバックURL
    →http://halcyonsystemblog.jp/tb.php/959-b36637fa
    この記事にトラックバックする(FC2ブログユーザー)