因为公司写了个IEntryDataObject的弱类型,
public interface IEntryDataObject : IDataObject
{
IEntryDataObject GetPropertyDataObject(string fieldName);
void SetPropertyValue(string fieldName, object value);
object GetPropertyValue(string fieldName);
IEnumerator<KeyValuePair<string, object>> GetProperties();
void SetDictionary(IDictionary dictionary);
void AddJsonObject(JObject jObject);
string GetKeyPropertyName();
string GetKeyId();
void SetKeyId(string keyId);
int GetPropertiesCount();
object GetFirstProperty();
void RemoveProperty(string fieldName);
}
public static T EntryDataObjectConvert<T>(IEntryDataObject entryDataObject) where T : class
{
var dataObject = System.Activator.CreateInstance<T>();
EntryDataObjectConvert(dataObject, entryDataObject);
return dataObject;
}
//这里有对PropertyInfo的详细使用
private static object EntryDataObjectConvert(object dataObject, IEntryDataObject entryDataObject)
{
var type = dataObject.GetType();
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
var propertyValue = entryDataObject.GetPropertyValue(propertyInfo.Name);
if (propertyValue != null)
{
object value;
if (propertyValue.GetType() == typeof (EntryDataObject))
{
var childType = propertyInfo.PropertyType;
var childDataObject = System.Activator.CreateInstance(childType);
var childEntryDataObject = propertyValue as IEntryDataObject;
value = EntryDataObjectConvert(childDataObject, childEntryDataObject);
}
else if (propertyValue.GetType() == typeof (List<EntryDataObject>) ||
propertyValue.GetType() == typeof (List<IEntryDataObject>))
{
var childListType = propertyInfo.PropertyType;
var childDataObjectList = System.Activator.CreateInstance(childListType);
var childEntryDataObjectList = propertyValue as List<IEntryDataObject>;
value = childDataObjectList;
if (childEntryDataObjectList != null)
{
foreach (var childEntryDataObject in childEntryDataObjectList)
{
var childType = childListType.GetGenericArguments()[0];
var childDataObject = System.Activator.CreateInstance(childType);
var result = EntryDataObjectConvert(childDataObject, childEntryDataObject);
//((IList) childDataObjectList).Add(result);
childListType.InvokeMember("Add",
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null,
childDataObjectList, new[] {result});
}
}
}
else
{
value = propertyValue;
}
propertyInfo.SetValue(dataObject, value, null);
}
}
return dataObject;
}