神圣的倒影

Holy Reflection

我收到一个错误,"unable to convert string to int?"。我觉得很奇怪,当您使用 PropertyInfo.SetValue 时,我的想法是它确实应该尝试使用该字段类型。

// Sample:
property.SetValue(model, null, null);

根据 Microsoft Developer Network 的 PropertyInfo.SetValue,以上内容将尝试在 属性 上实施 default(T)。但是,当我执行以下代码时:

// Sample:
property.SetValue(model, control.Value, null);

错误冒泡,当我为应该有 int? 的 属性 实现 string 时,我认为它会尝试自动解析指定的类型.我将如何帮助指定类型?

// Sample:
PropertyInfo[] properties = typeof(TModel).GetProperties();
foreach(var property in properties)
     if(typeof(TModel).Name.Contains("Sample"))
          property.SetValue(model, control.Value, null);

任何澄清以及如何解决转换都会有所帮助。为简洁起见修改了示例,尽量提供相关代码。

您必须将控件值转换为 属性 使用的类型 Convert.ChangeType():

if(typeof(TModel).Name.Contains("Sample"))  
   property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null);

更新:

在您的情况下,它是 Nullable 类型 (Nullable<int>),因此您必须以不同的方式进行操作,因为 Convert.ChangeType() 通常不适用于 Nullable 类型:

if(typeof(TModel).Name.Contains("Sample"))
{ 
  if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  {
     property.SetValue(model,Convert.ChangeType(control.Value, property.PropertyType.GetGenericArguments()[0]),null);
  }
  else
  {
    property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null);
  }