2016-09-28 10 views
2

私は複数の派生クラスによって継承された基本クラスを持っています。私はコンストラクタ内の基本クラスのいくつかのプロパティを初期化しています。派生クラスオブジェクトごとに同じプロパティ値を作成するのではなく、派生オブジェクトで基本クラスプロパティを共有できるようにする方法はありますか。基本クラスのプロパティ値の一部がサービスによって生成され、これを共有するとパフォーマンスが向上するため、これは本当に重要です。以下 はやや私が言うことをしようとしています何の簡単な青写真です:C#:派生オブジェクトを条件付きで同じ基本オブジェクトを共有する

public class ClassA 
{ 
    //i dont want to use static here as it will be shared for multiple codes 
    protected string country { get; set; } 
    public ClassA(string code) 
    { 
     country = CallsomeService(code); 
    } 
} 

public class ClassB : ClassA 
{ 
    public ClassB(string code) : base(code) 
    { 
     //blah blah 
    } 

    public void DomeSomethingWithCountry() 
    { 
     Console.WriteLine($"doing this with {country} in classB"); 
    } 
} 

public class ClassC : ClassA 
{ 
    public ClassC(string code) : base(code) 
    { 
     //blah blah 
    } 

    public void DomeSomethingWithCountry() 
    { 
     Console.WriteLine($"doing soemthing else with {country} in classC"); 
    } 
} 

は今ではなく、結果に静的にコールをしたのを格納することができ

 public void test() 
     { 
      //call service for this 
      var classb=new ClassB("1"); 
      //dont call service for this 
      var classc=new ClassC("1"); 
classb.DomeSomethingWithCountry(); 
classc.DomeSomethingWithCountry(); 
      //call service for this as code is different 
      var classb1=new ClassB("2"); 
     } 
+0

すべてのコードに対して静的にすると、常に同じ国が返されます – Unnie

+0

コンストラクタ内のオブジェクトの1つのインスタンスを渡して、 'Value' _(キャッシュ)_ –

+0

@SwagataPrateekこれらの基本クラスのプロパティが使用されます派生クラスのメソッドによって – Unnie

答えて

6

以下のようなオブジェクトを作ります値自体

public class ClassA 
{ 
    static Dictionary<string,string> codeToCountryLookup 
     = new Dictionary<string,string>(); 
    protected string country { get; set; } 
    public ClassA(string code) 
    { 
     if(!codeToCountryLookup.ContainsKey(code)) 
      codeToCountryLookup.Add(code,CallsomeService(code)); 
     country = codeToCountryLookup[code]; 
    } 
} 

これは決してスレッドセーフではありませんが、どこかで起動する必要があります。

+0

ディクショナリに特定のキーが含まれているかどうかを確認する前に、オブジェクトをロックするとどうなりますか?それはマルチスレッドの権利を助けることができますか? – kuskmen

+1

はい、マルチスレッドの状況を適切に処理しているだけですが、この質問の範囲外です。 – Jamiec

+0

これはまずは​​適切なオプションです。私は自分の投稿を更新しました。派生クラスのメソッドでこの国のプロパティを使用している場合はどうなりますか?次に、派生クラスのメソッドでこの正しい国を効率的に参照するにはどうすればいいですか? – Unnie

関連する問題