1

私がこのようなコードを持っているとしましょう:

public class Base  // I cannot change this class
{
    public string Something { get; private set; }
    public string Otherthing { get; set; }

    public static Base StaticPreSet
    {
        get { return new Base { Something = "Some", Otherthing = "Other"}; }
    }

    public static Base StaticPreSet2
    {
        get { return new Base { Something = "Some 2", Otherthing = "Other 2"}; }
    }
}

public class SubClass : Base  // I can change this class all I want.
{
    public string MoreData { get; set; }

    // How can I wrap the PreSets here so that they return SubClass objects?
    // Something like this:
    public static SubClass MyWrappedPreset 
    {
       get
       {
          // Code here to call the base preset and then use it as the 
          // base of my SubClass instance.
       }
    }
}

これを複雑にしているのは、Somethingプロパティです。プライベートセッターがあります。そのため、サブクラスに設定することはできません。設定できる唯一の方法は、プリセットプロパティを使用することです。

サブクラスタイプのオブジェクトを返すように、サブクラスのStaticPreSetプロパティをラップする方法はありますか?

4

2 に答える 2

2

// この基本クラスは変更できません。

基本クラスを変更できない場合、動作を変更する方法はありません (つまり、実行時に別のクラスを返す)。

基本クラスの静的メソッドの設計に影響を与えることができれば、この機能を提供するのに十分柔軟になるように再設計できます。ただし、これを変更しないと機能しません。


編集に応じて編集:

次のように、表示していることを実行する新しい静的メソッドを作成できます。

public static SubClass MyWrappedPreset 
{
   get
   {
      // Code here to call the base preset and then use it as the 
      // base of my SubClass instance.
       Base baseInstance = Base.StaticPreSet;
       SubClass sc = new SubClass(baseInstance); // Create a new instance from your base class
       return sc;
   }
}

ただし、これはまったく新しい無関係のプロパティを提供します。クラスSubClass.MyWrappedPresetではなく、を介してアクセスする必要があります。Base

于 2012-07-12T22:32:52.280 に答える