zoukankan      html  css  js  c++  java
  • C#关于通过反射PropertyType判读字符串类型方法

    今天在通过反射判读实体属性来映射数据库表是否修改的时候发现,最开始我通过

    p.GetValue(entity) == null && p.PropertyType.IsValueType
    

      来判断的时候,只能判断出实体中是否为值类型和null,如果满足就不会去修改该属性的值

    _dbContext.Entry<T>(entity).Property(p.Name).IsModified = false;
    

      但是在实际使用中发现,如果该model类中既有class实体类型,又有string类型将无法判断(string是值类型还是引用类型,可以看看该帖子http://www.cnblogs.com/yank/archive/2011/10/24/2204145.html说的比较详细),所以我们需要单独判断一下string类型,可能有人说通过IsNullOrEmpty来判断,那么我告诉你在通过反射来做的时候是行不通的,因为对应的属性值可能为null,通过IsNullOrEmpty判断class为null时直接回抛异常的,通Type.getType()也是行不通的,因为string a=null通过Type.getType(a)也会抛异常。所以还是需要通过PropertyType类型来判断,判断方式为 p.PropertyType == typeof(string) 这样即可判断出来。好了就到这里,部分代码如下,不喜勿喷。

      foreach (System.Reflection.PropertyInfo p in entity.GetType().GetProperties())
      {
          if (p.GetValue(entity) == null && (p.PropertyType.IsValueType || p.PropertyType == typeof(string)))
           {
                _dbContext.Entry<T>(entity).Property(p.Name).IsModified = false;
           }
       }
    

      

  • 相关阅读:
    Leetcode_02【两数相加】——【难度:中】
    Leetcode_39【组合总和】
    Leetcode_38【报数】
    Leetcode_36【有效的数独】
    Leetcode_35【搜索插入位置】
    51nod1347 旋转字符串
    WebH
    ExcelHelper
    文件二进制与String相互转换
    汇编语言里 eax, ebx, ecx, edx, esi, edi, ebp, esp
  • 原文地址:https://www.cnblogs.com/sysmenu/p/7570735.html
Copyright © 2011-2022 走看看