泛型参数T能否使用变量?
有一个泛型方法为:string GetDBXml<T>(object obj)
正常调用该方法为:string aa=GetDBXml<string>(obj);
现在的问题是:泛型方法中的类型T只能使用string、object等,而不能使用表达式的形式比如:getType(obj)。
请问调用泛型方法时,参数T要使用表达式的形式该如何解决?
--------------------编程问答--------------------
--------------------编程问答-------------------- 换成这样,
public class<T>:where T:string
{
string GetDBXml<T>(object obj)
{}
}
private string GetDBXml(object obj,Type t) --------------------编程问答-------------------- 写一个类,封装一下,类的初始化中实现表达式 --------------------编程问答-------------------- 不能直接用,但可以用反射。 --------------------编程问答-------------------- 反射得到 MethodInfo 对象
然后调用MakeGenericMethod方法。得到一个完整的方法。
然后Invoke --------------------编程问答-------------------- 那你何苦用泛型。。。 --------------------编程问答-------------------- 泛型方法的泛型参数一般的做法都是在编译时就确定了,
要在运行时去动态指定泛型参数,最直接的方法也就反射.
--------------------编程问答-------------------- 不要去 套
static void Main(string[] args)
{
MethodInfo mi = typeof(Program).GetMethod("GenericMethod", BindingFlags.Public | BindingFlags.Static);
if(mi !=null)
{
MethodInfo gmi = mi.MakeGenericMethod(typeof(string));
object o = gmi.Invoke(null, null);
Console.WriteLine(o);
}
Console.ReadLine();
}
static public string GenericMethod<T>()
{
return typeof(T).ToString();
}
灵活运用
补充:.NET技术 , C#