2014年6月1日日曜日

オブジェクトの初期化構文 - C#ショートプログラミング -

オブジェクトに初期値を与えたい


OLD
class Example
    {
        internal string A, B, C;
    }
    class Program
    {
        static void Main(string[] args)
        {
            var sample = new Example();
            sample.A = "{0} {1}";
            sample.B = "This is B!";
            sample.C = "This is C!";
            System.Diagnostics.Debug.WriteLine(sample.A, sample.B, sample.C);
        }
    }

NEW
//C#2.0
    class Example
    {
        internal string A, B, C;
    }
    class Program
    {
        static void Main(string[] args)
        {
            var sample = new Example()
            {
                A = "{0} {1}",
                B = "This is B!",
                C = "This is C!",
            };
            System.Diagnostics.Debug.WriteLine(sample.A, sample.B, sample.C);
        }
    }

Result

This is B! This is C!

・初期化専用構文
・インスタンスを明示しなくていいのでメンバー数が多いほど効果大

引用元:
C#ショートプログラミング





0 件のコメント:

コメントを投稿