【问题标题】:c# - how do I create this particular generic method?c# - 我如何创建这个特定的泛型方法?
【发布时间】:2011-07-06 02:37:33
【问题描述】:

我有一个表(我自己的不是DataTable)类女巫持有一个集合

   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,对象会做我也试过的伎俩 铸造类型抛出

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

【问题讨论】:

标签: c# generics type-conversion


【解决方案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});

    }

}

【讨论】:

    【解决方案2】:

    比 smartcaveman 短一点

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多