c# - 神圣的倒影

标签 c# asp.net asp.net-mvc reflection

我收到一个错误消息,“无法将字符串转换为整数?”。我觉得很奇怪,当您使用 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);
  }

关于c# - 神圣的倒影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636778/

相关文章:

c# - 清除函数中的 CheckBox 列表

asp.net-mvc - 更改 Active Directory 安全组和用户角色的时间滞后

JavaScript 不能在 PartialView 上运行

c# - Web API 2 RoutePrefix 不起作用

c# - 二维数组到一维并再次返回

c# - 为什么 is 或 as 运算符的左侧不允许使用 lambda 和匿名方法?

javascript - 鼠标悬停时显示 GridView 列名称的定义

c# - 客户关系管理 2011 : Wsdl web service doesn't contain my entities

c# - 请提供引用/指导以制作用于管理所有 IT Assets /设备的 Web 应用程序

asp.net-mvc - 使用 Entity Framework 我只想包含第一个子对象而不是子的子(子的子)