プロパティのなぞ

PlatformerのAnimation.csというのを読んでいたが、 なぜ

       public Texture2D texture;

としないで、

        public Texture2D Texture
        {
            get { return texture; }
        }
        Texture2D texture;

のように書くのだろうか。 publicな変数は体裁として極力プロパティとして公開するという意味か。 あるいは値を取り出すことはできるが、値をセットすることはできないようにするという意味か。 たぶん後者だろうな。

        public Animation(Texture2D texture, float frameTime, bool isLooping)
        {
            this.texture = texture;
            this.frameTime = frameTime;
            this.isLooping = isLooping;
        }

つまり、コンストラクタで生成するときしか値をセットできないということだわな。 ならpublic readonly変数にすればいいんじゃないのとか。

AnimationPlayer.cs。

        public Animation Animation
        {
            get { return animation; }
        }
        Animation animation;

これは紛らわしい。 Animationプロパティの宣言にAnimationクラスを使っている。 こういうのは普通なのか。

Circle.cs。

    struct Circle
    {
        /// 
        /// Center position of the circle.
        /// 
        public Vector2 Center;

        /// 
        /// Radius of the circle.
        /// 
        public float Radius;

        /// 
        /// Constructs a new circle.
        /// 
        public Circle(Vector2 position, float radius)
        {
            Center = position;
            Radius = radius;
        }

うーむ。こっちはプロパティじゃなくて変数をそのまま公開してるし。 しかも公開する変数名は頭文字大文字、プライベートなのは小文字ですか。 CenterやRadiusはそのまま値をセットしたり取り出せたりできるからってことなのか。 それとも単にコーディングスタイルの違い?

Enemy.cs。

        /// 
        /// How long this enemy has been waiting before turning around.
        /// 
        private float waitTime;

        /// 
        /// How long to wait before turning around.
        /// 
        private const float MaxWaitTime = 0.5f;

ふーむ。privateでも定数なら頭文字大文字ね。

Gem.cs。

        public const int PointValue = 30;
        public readonly Color Color = Color.Yellow;

ここのpublic constとpublic readonlyの違いはなんだっていうのはこのGem.csを読んでいるだけじゃわからんわな。 Platformer : パワーアップの追加 でコンストラクタを書き換えて、 Colorだけコンストラクタで値を書き換える必要があるからなんだな。 チュートリアル的には最初

public const Color Color = Color.Yellow;

にしておいて、

public readonly Color Color = Color.Yellow;

に書き換えさせたほうが良いんじゃないのかとか。

Layer.cs。

        public Texture2D[] Textures
        {
            get;
            private set;
        }

        public float ScrollRate
        { 
            get;
            private set;
        }

        public Layer(ContentManager content, string basePath, float scrollRate)
        { // 各レイヤーには 3 つのセグメントしかないものと仮定します。
            Textures = new Texture2D[3];
            for (int i = 0; i < 3; ++i)
                Textures[i] = content.Load(basePath + "_" + i);

            ScrollRate = scrollRate;
        }

プロパティってこういう使い方もできるんだなと。 これも基本的にはコンストラクタだけで値をセットできて、 外からはreadonlyに見えるってだけでしょう。 コーディングスタイルの違いってこと?