2011-07-06 15 views
1

は、私は(私自身ではないのDataTable)クラスの魔女は今Type値は私のアプリでのに私を助けるc# - この特定の汎用メソッドを作成するにはどうすればよいですか?

KeyValuePairs<string,Type> [] columns ; 

のコレクションを保持するテーブルを持っています。私は、「DB指数」 (B +ツリー)

を作成する必要がある場合たとえば、私は今、私は何のキーが

(そのタイプの)であろうフィールド魔女のタイプを必要としますこれを行うには、 によってそのインデックスを返すジェネリックメソッドを作成し、それが元のフィールドからテーブルの名前を取得することです。

以下のとおりであった分野は私の試みであろうタイプのか分からない方法を参照して、ツリー:

方法:

public BTree<T,object> CreateIndex<T>(string path,string FieldName) where T : IComparable 
メインで

(または、これまで):

Type index_type = table.Columns[2].Value;// the type 
    string field = table.Columns[2].Key; // the name of the field 
    BTree< 'type goes here',object> tree = CreateIndex<'type goes here'>(csv_path,field_name); 

タイプを抽出する方法が見つかりませんでした...

I thoug HTその自己INDEX_TYPEとして、それを入れて、オブジェクトが、私はまた、タイプをキャスト を試してみましたトリックを行うだろう

  Type.GetType(index_type.Name) 
     Type.GetType(index_type.FullName) 
     Type.GetType(index_type) 
     Type.GetType(index_type.GetType()) 

      index_type.GetType() by itself 

を投げたが、それはタイプとしてそれを除く外し得るように見える傾けます。 私はもちろん、すべてのものがうまく動作するタイプを与える場合。

 BTree<float,object> tree = reader.CreateIndex<float>(csv, field); 
+0

を必要としません汎用メソッドを呼び出しますか?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) –

+0

[csharpgeneral/thread](http://social.msdn.microsoft .com/Forums/en-US/csharpgeneral /スレッド/ fbacd5fd-829b -4db4-9bf8-5d1e0dab952b)は、リフレクションを使用して、ほぼ同じ質問のタイプを取得する方法を示しています。 –

答えて

1
// the class that contains the CreateIndex<T> method. Note that you will have to change the BindingFlags if this method is static 

public class IndexCreator 
{ 

    // your method 
    public BTree<T, object> CreateIndex<T>(string path, string fieldName) 
      where T : IComparable 
    { 
     // method body 
    } 

    // generic method 
    public object CreateIndex(Type indexType, string path, string fieldName) 
    { 
     var genericMethod = GetType() 
      .GetMethods(BindingFlags.Public | BindingFlags.Instance) 
      .Single(methodInfo => methodInfo.Name == "CreateIndex" && methodInfo.IsGenericMethodDefinition) 
      .MakeGenericMethod(indexType); 
     return genericMethod.Invoke(this, new object[]{path, fieldName}); 

    } 

} 
0

smartcavemanより少し短い

Activator.CreateInstance(typeof(BTree<>).MakeGenericType(indextype, typeof(object)), new object[]{arguments to constructor}) 

だろうが、それはあなたがおそらくにリフレクションを使用する方法[このは役に立ち見つけるクラスとデフォルトコンストラクタ

関連する問題