簡體   English   中英

c# - 我如何創建這個特定的通用方法?

[英]c# - how do I create this particular generic method?

我有一張表(我自己的不是DataTable)class 女巫擁有一個集合

   KeyValuePairs<string,Type> [] columns ;

現在類型值輔助是我在我的應用程序中的。 例如,當我需要創建“數據庫索引”(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);  

我無法找到提取類型的方法...

我想把它作為它自己的 index_type,object 會做的伎倆我也嘗試過投擲類型

         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); 
// 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});

    }

}

比 smartcaveman 短一點

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

但它確實需要 class 和默認構造函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM