0

次のコードを単純化する方法を教えてくれる人はいますか

            private bool isMethodCalled;
            private void CallMethod()
            {
                if (!isMethodCalled)
                {
                    this.CallCertainMethod();
                    isMethodCalled = true;
                }
            }

            private int field1;
            public int Property1
            {
                get
                {
                    CallMethod();
                    return this.field1;
                }
                set { this.field1 = value; }
            }

           private int field2;
            public int Property2
            {
                get
                {
                    CallMethod();
                    return this.field2;
                }
                set { this.field2 = value; }
            }


            private int field3;
            public int Property3
            {
                get
                {
                    CallMethod();
                    return this.field3;
                }
                set { this.field3 = value; }
            }
4

2 に答える 2

1

You could use an AOP framework like PostSharp to create an attribute which would call CallMethod and just use automatic properties for Property1, Property2 and Property3. Although it wouldn't save much in the number of lines of code unless there are a lot of other properties.

于 2012-06-14T15:45:18.547 に答える
1

単純化できるものは次のとおりです。

private void CallMethod()
{
    if (!isMethodCalled)
    {
        this.CallCertainMethod();
        isMethodCalled = true;
    }
}

に:

private void CallMethod()
{
    if (!isMethodCalled) this.CallCertainMethod();
    isMethodCalled = true;
}

補足として:

私は何をするかわかりませんCallCertainMethod()。念のため、データのクエリと状態の変更を同時に行うことはお勧めしません。Command Query-Separationを参照してください。すべてのメソッドは、アクションを実行するコマンド、または呼び出し元にデータを返すクエリのいずれかである必要がありますが、両方である必要はありません。言い換えれば、質問をしても答えが変わるべきではありません。

于 2012-06-14T15:47:29.077 に答える