A sample :Type type=Type.GetType("System.Data.SqlClient.SqlCommand"); MessageBox.Show(type.FullName);//运行出错?--- Type type=(new System.Data.SqlClient.SqlCommand()).GetType(); MessageBox.Show(type.FullName);//运行不出错?
Type t = Type.GetType("System.Data.SqlClient.SqlDataAdapter,System.Data,Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");注意字符串的写法,不是本装配件或者mscorlib.dll中定义的类型必须加上装配件的信息
Type type=typeof(System.Data.SqlClient.SqlDataAdapter);
timmy3310(Tim) is right.Type.GetType always searches in the calling assembly and mscorlib.dll if no assembly name provided in the string parameter. So System.String could be found at mscorlib.dll but System.Data.SqlClient.SqlDataAdapter can't.You have to provide the assembly name in form of "Full Qualified Type Name". For Types defined in private non-Strongnamed assembly, it's the type name plus the assembly file name without extension. For Strong Named assembly, it's type name plus the assembly name, with version, culture and public key information.Read Res section of Type.GetType(string) in MSDN.
但我想不通了 为什么他们的实例GetType就可以呢???
MessageBox.Show(type.FullName);//运行出错?---
Type type=(new System.Data.SqlClient.SqlCommand()).GetType();
MessageBox.Show(type.FullName);//运行不出错?
你在使用GetType的方法时也有两种,对对值类型你可能直接使用Type.GetType("")得到,
但是对地引用类型你必须创建实例,然后使用实例的GetType方法,
System.Data.SqlClient.SqlCommand 非静态类,自身是一个对象,对type 而言是一个被动类型,只能在受实例化作用下(由于对象类型引用产生TYPE)才具备gettype() 所需要的值(Type),所以必须实例化
同意!!!!!
Object.GetType的工作方式和上面的不同。因为你已经得到了对象实例(object),也就意味着在这之前你已经通过某种方式把定义对象的Assembly加载捣内存里了,不需要额外的信息来确定定义类型的Assembly。
中已经解释的很好了。
Type t = Type.GetType("System.String, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
因为属于mscorlib,所以也可以:t = Type.GetType("System.String");但SqlDataAdapter必须指定Assembly名:
t = Type.GetType("System.Data.SqlClient.SqlDataAdapter, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
using System.Reflection;public static void Test()
{
Type type = Type.GetType("DbTable2cs.Change"); Assembly ass = Assembly.GetAssembly(type); Object obj = ass.CreateInstance("DbTable2cs.Change"); //转换为Change,调用方法
Change change = (Change)obj; change.WriteSomeThing(); //使用方法名,调用方法
MethodInfo mi = type.GetMethod("WriteSomeThing");
object s2 = mi.Invoke(obj,null);
}
Type t = typeof(System.Data.SqlClient.SqlDataAdapter);
因为不明白方法的参数信息ParameterInfo[]怎么动态使用。虽然MethodInfo可以取得参数信息,但是怎么用呢?调用者是不知道参数类型的,知道的最多是参数个数,它可以提供参数,很可能全部用string类型的。我该怎么根据MethodInfo.GetParameters()取得的参数信息把STRING类型的参数全部转换成所需参数啊?如果我不能转换,动态调用岂不是一句空话?
如果你要“完全”动态的调用的话,可以用Activator.CreateInstance建立符合参数类型的对象作为参数。