0

理想的にはリフレクションを使用せずに、後で読み取り/書き込みを行うために、オブジェクトのプロパティへの参照を保存できる必要があります。私はまた、機能する設計パターンにもオープンですが、私のアプリケーションはさまざまな「親」クラスで「実行」するために何百万もの呼び出しを行うため、パフォーマンスが最も重要です。以下のコード テンプレートは、私がやろうとしていることを説明する必要があります。

たとえば、「必要な」変数が Child クラスのオブジェクト プロパティであり、リストに格納されているデータ構造ではないようにしたいと考えています。

最後に、オブジェクトの値をリセットしたり、null でないことを確認したりするだけにとどまらないものを探していると思います。たとえば、_run を呼び出した後、Parent はプロパティの値を別の用途に使用する場合があります。

ありがとうございました。

class requiredAttribute : Attribute
{
}

abstract class Parent
{
    abstract protected void _run();

    public Parent() {
        // This can do whatever set-up is necessary in order to make the below run() call
        // not need reflection.

        /* What code goes here? */
    }

    public void run() {
        // This code should reset all 'required' properties to null.
        /* What goes here? */

        _run();

        // This code needs to ensure any required property is now not null.
        // If it finds a null one, it should throw.
        /* What goes here? */
    }
}

class Child : Parent
{
    [required]
    protected object value1;
    [required]
    protected object value2;

    // not required..
    protected object value3;

    protected void _run() {
        // This must set all 'required' properties' values, otherwise the Parent should throw.
        value1 = "some value";
        value2 = "some other value";
    }
}
4

3 に答える 3

0

属性を使用するのではなく、インターフェイスを使用します。

インターフェイスIValidatableを作成し、親に配置します。
親にそれの抽象的な実装を与えます。そしてそれを子供に実装します。

abstract class Parent : IValidatable
{
    public abstract bool IsValid();
    abstract protected void _run();

    public Parent()
    {
    }

    public void run()
    {
        _run();

        if (!IsValid())
            //throw
    }
}

class Child : Parent
{
    protected object value1;
    protected object value2;

    // not required..
    protected object value3;

    protected override void _run()
    {
        // This must set all 'required' properties' values, otherwise the Parent should throw.
        value1 = "some value";
        value2 = "some other value";
    }

    public override bool IsValid()
    {
        return value1 != null && value2 != null;
    }
}

public interface IValidatable
{
    bool IsValid();
}
于 2013-09-15T01:30:26.047 に答える