c# 對象反射賦值未知屬性需類型轉換


反射某個類時,對於類的屬性,字段。已知有已知的方法,未知有未知的寫法。

而SetValues賦值則需要類型轉換

情況1,該屬性類型是已知類型,例如:int

int value=500;
property.SetValue(obj,value,null);

  

這里需要注意value值的類型必須和屬性類型一致,否則會拋出TargetException異常。

 

情況2,該屬性類型是已知類型,原值是其他類型。例如:目標類型為int,值為string

string value="500";
property.SetValue(obj,int.TryParse(value),null);//類型轉換

 

情況3,該屬性類型是未知非泛型類型,不確定目標類型,如何進行類型轉換

object value="500";
property.SetValue(obj,Convert.ChangeType(value,property.PropertyType),null);//類型轉換

  

這是在非泛型情況,

若是泛型則加個判斷吧

 1     if (!property.PropertyType.IsGenericType)
 2             {
 3                 //非泛型
 4                 property.SetValue(obj, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, property.PropertyType), null);
 5             }
 6             else
 7             {
 8                 //泛型Nullable<>
 9                 Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
10                 if (genericTypeDefinition == typeof(Nullable<>))
11                 {
12                     property.SetValue(obj, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(property.PropertyType)), null);
13                 }
14             }

 

貼個案例源代碼:

1             var discount = "111";
2             Type t = obj.GetType();
3             PropertyInfo pi = t.GetProperty("discount");
4             if (pi != null)
5                 pi.SetValue(obj, Convert.ChangeType(discount, pi.PropertyType), null);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM