Getmethod 调用失败并出现异常
Getmethod Invoke fails with exception
我正在尝试从我的静态函数中调用 get_ConnectionString 方法。但是我遇到了异常。
我的代码如下
PropertyInfo[] myPropertyInfo;
var ss = Type.GetType("System.Data.SqlClient.SqlConnection,System.data, version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false, true);
myPropertyInfo = ss.GetProperties();
for (int i = 0; i < myPropertyInfo.Length; i++)
{
System.IO.StreamWriter sw = System.IO.File.AppendText("C:\Temp\out.txt");
if(myPropertyInfo[i].GetMethod.ToString().Contains("get_ConnectionString") == true)
{
var obj1 = myPropertyInfo[i].GetMethod.Invoke(null,null);
sw.WriteLine(obj1);
}
sw.Close();
}
以上代码应在 out.txt 文件中写入连接字符串。但是我遇到了异常
System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object
target)
我怎样才能完成这项工作?我在这里做错了什么?
您需要传递对象实例以调用该方法:Invoke(sqlConnection, null)
。错误消息具有误导性。
我正在尝试从我的静态函数中调用 get_ConnectionString 方法。但是我遇到了异常。
我的代码如下
PropertyInfo[] myPropertyInfo;
var ss = Type.GetType("System.Data.SqlClient.SqlConnection,System.data, version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false, true);
myPropertyInfo = ss.GetProperties();
for (int i = 0; i < myPropertyInfo.Length; i++)
{
System.IO.StreamWriter sw = System.IO.File.AppendText("C:\Temp\out.txt");
if(myPropertyInfo[i].GetMethod.ToString().Contains("get_ConnectionString") == true)
{
var obj1 = myPropertyInfo[i].GetMethod.Invoke(null,null);
sw.WriteLine(obj1);
}
sw.Close();
}
以上代码应在 out.txt 文件中写入连接字符串。但是我遇到了异常
System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
我怎样才能完成这项工作?我在这里做错了什么?
您需要传递对象实例以调用该方法:Invoke(sqlConnection, null)
。错误消息具有误导性。