神圣的反思

Gre*_*reg 5 c# asp.net reflection asp.net-mvc

我收到一个错误,"无法将字符串转换为int?" .我觉得很奇怪,当你利用PropertyInfo.SetValue它时,我的想法确实应该尝试使用那种字段类型.

// Sample:
property.SetValue(model, null, null);
Run Code Online (Sandbox Code Playgroud)

以上将default(T)根据PropertyInfo.SetValueMicrosoft Developer Network 尝试在该属性上实现.但是,当我实现以下代码时:

// Sample:
property.SetValue(model, control.Value, null);
Run Code Online (Sandbox Code Playgroud)

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

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

任何澄清以及如何解决演员阵容都会有所帮助.为简洁起见,对示例进行了修改,尝试提供相关代码.

Ehs*_*jad 3

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

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

更新:

在您的情况下,它是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);
  }
Run Code Online (Sandbox Code Playgroud)