c# - 如何创建这种特殊的通用方法?

时间:2011-07-06 02:37:34

标签: c# generics type-conversion

我有一个表(我自己不是DataTable)类拥有

的集合
   KeyValuePairs<string,Type> [] columns ;

现在Type值在我的应用程序中帮助了我。例如,当我需要创建“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);  

我无法找到提取类型的方法......

我认为把它作为自己的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); 

2 个答案:

答案 0 :(得分: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});

    }

}

答案 1 :(得分:0)

比smartcaveman短一点

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

但它确实需要一个类和一个默认构造函数