[英]Setting properties of an object through reflection with different properties types
我使用反射來填充對象的屬性。
這些屬性有不同的類型:String,Nullable(double)和Nullable(long)(不知道如何在這里轉義尖括號......)。 這些屬性的值來自(字符串,對象)對的字典。
因此,例如我的類具有以下屬性:
string Description { get; set; }
Nullable<long> Id { get; set; }
Nullable<double> MaxPower { get; set; }
(實際上有大約十幾個屬性),字典將有<“描述”,“描述”>,<“Id”,123456>,<“MaxPower”,20000>等條目
現在我使用類似以下內容來設置值:
foreach (PropertyInfo info in this.GetType().GetProperties())
{
if (info.CanRead)
{
object thisPropertyValue = dictionary[info.Name];
if (thisPropertyValue != null && info.CanWrite)
{
Type propertyType = info.PropertyType;
if (propertyType == typeof(String))
{
info.SetValue(this, Convert.ToString(thisPropertyValue), null);
}
else if (propertyType == typeof(Nullable<double>))
{
info.SetValue(this, Convert.ToDouble(thisPropertyValue), null);
}
else if (propertyType == typeof(Nullable<long>))
{
info.SetValue(this, Convert.ToInt64(thisPropertyValue), null);
}
else
{
throw new ApplicationException("Unexpected property type");
}
}
}
}
所以問題是:在分配值之前,我真的必須檢查每個屬性的類型嗎? 有什么像我可以執行的強制轉換,以便為屬性值分配相應屬性的類型?
理想情況下,我希望能夠做類似以下的事情(我天真地認為可能有用):
if (thisPropertyValue != null && info.CanWrite)
{
Type propertyType = info.PropertyType;
if (propertyType == typeof(String))
{
info.SetValue(this, (propertyType)thisPropertyValue, null);
}
}
謝謝,斯特凡諾
如果值已經是正確的類型,那么否:您不必做任何事情。 如果它們可能不對(int vs float等),一個簡單的方法可能是:
( 編輯調整為空)
Type propertyType = info.PropertyType;
if (thisPropertyValue != null)
{
Type underlyingType = Nullable.GetUnderlyingType(propertyType);
thisPropertyValue = Convert.ChangeType(
thisPropertyValue, underlyingType ?? propertyType);
}
info.SetValue(this, thisPropertyValue, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.