反射取得物件の入れ物
-
05-09-2019 - |
質問
とは: 反射-設定の種類の返されたobj? いオブジェクトコJobcard数特性、別のオブジェクトというお客様独自の特性を、他の子と呼ばれるオブジェクト所在地.
これらの2つの機能を取り扱いその他のオブジェクト型です。
private T PopulateObject<T>(T dataObj, System.Data.DataRow dataRow)
{
//Type type = dataObj.GetType();
System.Reflection.PropertyInfo[] proplist = dataObj.GetType().GetProperties();
foreach ( System.Reflection.PropertyInfo propertyitem in proplist)
{
if(propertyitem.Name != "")
//s += propertyitem.Name + ":" + (propertyitem.GetValue(dataObj,null)).ToString() + "\r\n";
try
{
propertyitem.SetValue(dataObj, dataRow[propertyitem.Name], null);
}
catch (Exception ex)
{
if (ex.Message.Contains("does not belong to table"))
{
propertyitem.SetValue(dataObj, PopulateChildObject(propertyitem, dataRow), null);
}
else
throw;
}
}
return dataObj;
}
private object PopulateChildObject(object dataObj, System.Data.DataRow dataRow)
{
System.Reflection.PropertyInfo[] proplist = dataObj.GetType().GetProperties();
foreach ( System.Reflection.PropertyInfo propertyitem in proplist)
{
if(propertyitem.Name != "")
try
{
propertyitem.SetValue(dataObj, dataRow[propertyitem.Name], null);
}
catch (Exception ex)
{
if (ex.Message.Contains("does not belong to table"))
{
propertyitem.SetValue(dataObj, PopulateChildObject(propertyitem, dataRow), null);
}
else
throw;
}
}
return dataObj;
}
問題は、PopulateChildObject機能は働きませんのでPropertyInfo一覧を非表示にするには、渡されたchildObj.眺めれば、dataObj渡PopulateChildObjectの時計で0属性です。また、dataObj渡PopChildObj()がタイプのシステム。反射を生み出します。RuntimePropertyInfoくことができるようになりのタイプおります。と思欠?
解決
propertyitem
は PropertyInfo
;渡す必要がありますの 値 かに-(
propertyItem.GetValue(dataObj, null);
この子オブジェクトが作成され、親ん"を行う必要がありセット"でだけを更新underylingオブジェクト:
PopulateChildObject(propertyitem.GetValue(dataObj, null), dataRow);
するに必要なもの の作成 の子オブジェクト(通常 Activator.CreateInstance
る場合には、お ま 電話をする必要があり SetValue
:
object child = propertyitem.GetValue(dataObj, null);
if(child == null) {
child = Activator.CreateInstance(propertyitem.PropertyType);
propertyitem.SetValue(dataObj, child, null);
}
PopulateChildObject(child, dataRow);
かなぁ、というものがあっ違い PopulateObject
や PopulateChildObject
?のようになっている場合には、その同じこんなことをしたのだろう。
他のヒント
例えば巣のプロパティを取得し、Developer.Project.Name
private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName)
{
if (t.GetType().GetProperties().FirstOrDefault(p => p.Name == PropertName.Split('.')[0]) == null)
throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString()));
if (PropertName.Split('.').Length == 1)
return t.GetType().GetProperty(PropertName);
else
return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1]);
}
所属していません StackOverflow