2016-09-01 7 views
1

そのタイプによってクラスのインスタンスを起動します生成:私は任意の型を受け入れ、私は後でそれを使用できるように、そのインスタンスを作成しますジェネリックメソッドを記述しようとしています

public class bb_ColorScaleCriteriaTypes 
    { 
     public Dictionary<string, int> Types { get; set; } 
     public bb_ColorScaleCriteriaTypes() 
     { 
      this.Types = new Dictionary<string, int>() 
      { 
       {"LowestValue", 1}, 
       {"Number", 0}, 
       {"Percent", 3}, 
       {"Formula", 4}, 
       {"Percentile", 5}, 
       {"HighestValue", 2}, 
       {"AutomaticMax", 7}, 
       {"AutomaticMin", 6}, 
       {"None", -1} 
      }; 
     } 

     public static int byName(string name) 
     { 
      if (name == null) 
      { 
       throw new ArgumentException("name"); 
      } 
      int intValue = new bb_ColorScaleCriteriaTypes().Types[name]; 
      return intValue; 
     } 
    } 

通常、私は、私はこのように呼び出すことができる別のクラスがあります:あなたは私がbb_ColorScaleCriteriaTypesのクラスをインスタンス化して、上のタイプを呼び出しています見ることができるように

public class bb_ColorScaleCriteriaTypesUI : DSDropDownBase 
    { 
     private const string NO_FAMILY_TYPES = "No types were found."; 
     public bb_ColorScaleCriteriaTypesUI() : base("Color Scale Criteria Type") { } 

     // Get Data Class that holds dictionary 
     public static bb_ColorScaleCriteriaTypes cscTypes = new bb_ColorScaleCriteriaTypes(); 

     protected override SelectionState PopulateItemsCore(string currentSelection) 
     { 
      Items.Clear(); 

      Dictionary<string, int> d = new Dictionary<string, int>(cscTypes.Types); 
     } 

を それ。しかし、私はちょうどこれに似た何かをすることができ、より一般的な実装を書きたい:これは本当に速いコメントで手の少し外を得たよう

public abstract class bb_ColorScaleCriteriaTypesUI : DSDropDownBase 
    { 
     public bb_ColorScaleCriteriaTypesUI (string name, Type elementType) : base(name) { this.ElementType = elementType; PopulateItems(); } 

     private const string noTypes = "No Types available."; 
     public Type ElementType; 

     // how to instantiate an instance of ElementType here? 

     protected override SelectionState PopulateItemsCore(string currentSelection) 
     { 
      if (this.ElementType != null) 
      { 
      Dictionary<string, int> d = new Dictionary<string, int>(myTypeInstance.Types); //so I can call it here 
     } 

が見えます。

とにかく、私はActivator.CreateInstanceを()を使用して、気にしませんが、どのように私はタイプのインスタンスを作成することができ、そのない汎用オブジェクトので、型に戻ってそれをキャスト?他の人が言っているよう

+0

はサウンズ[Activator.CreateInstance()](https://msdn.microsoft.com/en-us/library/system.activator.createinstance(V = vs.110).aspxの)。 – itsme86

答えて

3

Activator.CreateInstance()。戻り値の型は、その実際の型は、あなたが要求し、一般的なオブジェクトではありません、そのことが、すべての基底クラスだからちょうどオブジェクトとして返されます。

「正しい方法」を実行したい場合は、すべてのクラスが導出/実装するインターフェイスまたはベースクラスを定義し、インターフェイス/ベースで一般的に定義する必要がある共通メソッドを使用しますクラス。そして、あなたは最高の新しいオブジェクトにActivator.CreateInstance()またはファクトリパターンを使用し、インターフェース/基本クラスとしてそれらを返すことができます。あなたが探しているよう

+0

は、私は以下の投稿をサンプルのための任意のアイデアを持っていますか?私はあなたの提案に従うことを試みていますが、別のロードブロッキングを打ちました。 – konrad

関連する問題

 関連する問題