我正在尝试获取带有反射的浮点属性,并使用其tostring(iformatProvider(方法设置另一个属性,类型为字符串。我得到"反射。targetException,对象不匹配目标类型"错误。我将在下面放一些代码来解释:
public class myForm : Form
{
public float myFloat { get; set; } = 2.78f;
public string myString { get; set; } = "127";
private void button2_Click(object sender, EventArgs e)
{
//Get "myFloat" property of this instance of Form.
PropertyInfo myfloat_property = this.GetType().GetProperty("myFloat");
//Get ToString(IFormatProvider) method of the "myFloat" property.
MethodInfo to_string = myfloat_property.PropertyType.GetMethod("ToString", new Type[] { typeof(IFormatProvider) });
//Set "myString" property. Where i get the exception.
myString = (string)to_string.Invoke(myfloat_property, new object[] { CultureInfo.InvariantCulture });
}
}
我想我缺少一些容易看到的东西。但是我现在看不到,你能告诉我吗?
谢谢大家。
当您将错误的this
对象传递给Invoke()
方法时,您会遇到该错误
在您的情况下,这是因为您正在传递PropertyInfo
对象myfloat_property
,而实际上您应该传递属性本身的值。例如:
public class myForm : Form
{
public float myFloat { get; set; } = 2.78f;
public string myString { get; set; } = "127";
private void button2_Click(object sender, EventArgs e)
{
//Get "myFloat" property of this instance of Form.
PropertyInfo myfloat_property = this.GetType().GetProperty("myFloat");
//Get ToString(IFormatProvider) method of the "myFloat" property.
MethodInfo to_string = myfloat_property.PropertyType.GetMethod("ToString", new Type[] { typeof(IFormatProvider) });
//Set "myString" property. Where i get the exception.
myString = (string)to_string.Invoke(myfloat_property.GetValue(this), new object[] { CultureInfo.InvariantCulture });
}
}
现在,就是说,您的问题中有几件事不清楚。以上代码将解决例外。但这似乎并不是实现最终结果的最佳方法。例如,您已经可以访问该属性本身,因此,您可以直接使用该属性,而不是使用PropertyInfo
对象:
public class myForm : Form
{
public float myFloat { get; set; } = 2.78f;
public string myString { get; set; } = "127";
private void button2_Click(object sender, EventArgs e)
{
//Get ToString(IFormatProvider) method of the "myFloat" property.
MethodInfo to_string = myFloat.GetType().GetMethod("ToString", new Type[] { typeof(IFormatProvider) });
//Set "myString" property. Where i get the exception.
myString = (string)to_string.Invoke(myFloat, new object[] { CultureInfo.InvariantCulture });
}
}
,但即使这似乎过于复杂。毕竟,不仅可以访问该属性,ToString()
方法也是如此。因此,您的方法实际上可能看起来像这样:
public class myForm : Form
{
public float myFloat { get; set; } = 2.78f;
public string myString { get; set; } = "127";
private void button2_Click(object sender, EventArgs e)
{
myString = myFloat.ToString(CultureInfo.InvariantCulture);
}
}
根本不需要反射。也不例外。:(