C# Propertyinfo目标异常对象上的SetValue与目标类型不匹配错误
我试图为属性设置一个值,但我得到的目标异常对象始终与目标类型错误不匹配 属性类C# Propertyinfo目标异常对象上的SetValue与目标类型不匹配错误,c#,C#,我试图为属性设置一个值,但我得到的目标异常对象始终与目标类型错误不匹配 属性类 class WizardProperties { public int IncIncidentType { get; set; } } 尝试设置属性值的代码段 public void _wizardControl_NextButtonClick(object sender, WizardCommandButtonClickEventArgs e) { foreach (Contro
class WizardProperties
{
public int IncIncidentType { get; set; }
}
尝试设置属性值的代码段
public void _wizardControl_NextButtonClick(object sender, WizardCommandButtonClickEventArgs e)
{
foreach (Control c in e.Page.Controls)
{
WizardProperties props = new WizardProperties();
SearchLookUpEdit slue = new SearchLookUpEdit();
foreach (var property in props.GetType().GetProperties())
{
if (!(c is Label))
{
if (property.Name == c.Name)
{
MessageBox.Show("Matchhh!!");
if (c is SearchLookUpEdit)
{
slue = (SearchLookUpEdit)c;
}
PropertyInfo info = props.GetType().GetProperty(property.Name);
int type = Convert.ToInt32(slue.EditValue);
info.SetValue(property,type,null);
}
}
}
}
}
属性在单独的类中声明,错误发生在:info.SetValueproperty,type,null。在搜索此错误时,我添加了null作为找到的第三个参数解决方案,但这对我不起作用。类型变量具有有效的int。
如何修复设置值行
编辑:简单更改
info.SetValue(property,type,null);
到
修复了错误看起来您试图在表示要设置的属性的PropertyInfo对象上设置属性值,而不是在作为类实例的props上设置属性值。您还在第二次检索PropertyInfo,同时循环遍历props的属性,所以我已经删除了它。我还假设,一旦代码开始工作,您实际上将使用道具做一些事情。试试下面
foreach (Control c in e.Page.Controls)
{
WizardProperties props = new WizardProperties();
SearchLookUpEdit slue = new SearchLookUpEdit();
foreach (var property in props.GetType().GetProperties())
{
if (!(c is Label) && property.Name == c.Name)
{
MessageBox.Show("Matchhh!!");
if (c is SearchLookUpEdit)
{
slue = (SearchLookUpEdit)c;
}
int type = Convert.ToInt32(slue.EditValue);
property.SetValue(props,type,null);
}
}
}
我发现当时试图设置属性的值是导致错误的原因。我会将您的答案标记为已接受,因为您还优化了我的代码。谢谢你。
foreach (Control c in e.Page.Controls)
{
WizardProperties props = new WizardProperties();
SearchLookUpEdit slue = new SearchLookUpEdit();
foreach (var property in props.GetType().GetProperties())
{
if (!(c is Label) && property.Name == c.Name)
{
MessageBox.Show("Matchhh!!");
if (c is SearchLookUpEdit)
{
slue = (SearchLookUpEdit)c;
}
int type = Convert.ToInt32(slue.EditValue);
property.SetValue(props,type,null);
}
}
}