c# - how do I create this particular generic method?
I have a table (my own not DataTable) class witch holds a collection of
KeyValuePairs<string,Type> [] columns ;
now the Type value assist's me in my app. for example when i need to create a "DB ind开发者_如何学Cex" ( a B+tree )
I require the type of the field witch the key would be of ( of its type )
Now what I'm attempting to do is create a generic method which would return that index by acquiring the name of the field and the table from witch it is from.
The tree referencing the method does not know what type the field would be of my attempt was as follows :
the method :
public BTree<T,object> CreateIndex<T>(string path,string FieldName) where T : IComparable
in main ( or where ever ) :
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 wasn't able to find a way to extract the type ...
I thought putting it as it self index_type, object would do the trick i also tried casting the type threw
Type.GetType(index_type.Name)
Type.GetType(index_type.FullName)
Type.GetType(index_type)
Type.GetType(index_type.GetType())
index_type.GetType() by itself
but cant seem to get it to except it as a type. if I of course give the type every thing works fine.
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});
}
}
A bit shorter than smartcaveman would be
Activator.CreateInstance(typeof(BTree<>).MakeGenericType(indextype, typeof(object)), new object[]{arguments to constructor})
but it does require a class and a default constructor
精彩评论