1

我嘗試構建一個通用方法,它使用反射類和設置值並返回類類型。如何使用反射設置屬性值?

protected static T GetSecureModel<T>(T model) 
     { 
      T secureModel = default(T); 

      foreach (var property in model.GetType().GetProperties()) 
      { 

        if (string.CompareOrdinal(property.PropertyType.FullName, "System.String") == 0) 
        { 
         property.SetValue(property.Name, property.GetValue(model, null).ToString(), null); 
        } 
      } 

       return secureModel; 
} 

如何在set值後返回Class?

回答

2

好的。我解決它。檢查下面的代碼,這可能對某人有幫助。

protected static T GetSecureModel<T>(T model) 
     { 
      bool secureData = false; 

      T secureModel = default(T); 

      foreach (var property in model.GetType().GetProperties()) 
      { 
       if (property.GetValue(model, null) != null && property.GetValue(model, null).ToString() != _blankGuid && property.GetValue(model, null).ToString() != _zero) 
       { 
        if (string.CompareOrdinal(property.PropertyType.FullName, _uniqueIdentifier) == 0) 
        { 
         model.GetType().GetProperty(property.Name).SetValue(model, new Guid(Sanitizer.GetSafeHtmlFragment(property.GetValue(model, null).ToString())), null); 
        } 
        else if (string.CompareOrdinal(property.PropertyType.FullName, _numeric) == 0) 
        { 
         model.GetType().GetProperty(property.Name).SetValue(model, int.Parse(Sanitizer.GetSafeHtmlFragment(property.GetValue(model, null).ToString())), null); 
        } 
        else if (string.CompareOrdinal(property.PropertyType.FullName, _string) == 0) 
        { 
         model.GetType().GetProperty(property.Name).SetValue(model, Sanitizer.GetSafeHtmlFragment(property.GetValue(model, null).ToString()), null); 
        } 

        secureData = true; 
       } 

      } 

      if (secureData) 
      { 
       secureModel = model; 
      } 

      return secureModel; 
     }