[英]C# Reflection & Generics
有一個復雜的反思問題。 給定下面的代碼,您將如何實現該偽函數,以便在給定Parent實例的情況下,將枚舉類型Properties來查找具有與Parent類型相同的Property的子對象,並將引用設置為所提供的p。 希望有道理。 另外,我還需要使用它來處理通用列表。 請參閱下面的示例對象圖。 運行此命令后,子Pet實例中的每個Person將成為Parent實例。
public class ChildSetter<Parent>
{
public void Set(Parent p)
{
//pseudo
//var parentName = p.GetType().Name;
//foreach (var property in p.Properties)
//{
// if (!property.IsList)
// {
// if (property.ContainsProperty(parentName))
// property.Properties[parentName] = p;
// }
// else
// {
// if (property.ListType.ContainsProperty(parentName))
// {
// foreach (var item in property)
// {
// item.Properties[parentName] = p;
// }
// }
// }
//}
}
}
public class Person
{
public Pet Pet { get; set; }
public IList<Pet> Pets { get; set; }
}
public class Pet
{
public Person Person { get; set; }
}
該代碼的一個非通用示例如下:
public void Set(Person p)
{
p.Pet.Person = p;
foreach (var pet in p.Pets)
{
pet.Person = p;
}
}
我還沒有測試過,但是如何:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
static class Program
{
static void Main()
{
...
}
public static void SetParent<T>(T root)
{
foreach (PropertyInfo prop in typeof(T).GetProperties
(BindingFlags.Public | BindingFlags.Instance))
{
if (!prop.CanRead) continue;
Type listType = null;
foreach (Type interfaceType in prop.PropertyType.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IList<>))
{ // IList<T> detected
listType = interfaceType.GetGenericArguments()[0];
}
}
List<PropertyInfo> propsToSet = new List<PropertyInfo>();
foreach (PropertyInfo childProp in (listType ?? prop.PropertyType).GetProperties(
BindingFlags.Public | BindingFlags.Instance))
{
if (childProp.PropertyType == typeof(T)) propsToSet.Add(childProp);
}
if(propsToSet.Count == 0) continue; // nothing to do
if (listType == null)
{
object child = prop.GetValue(root, null);
if (child == null) continue;
foreach (PropertyInfo childProp in propsToSet)
{
childProp.SetValue(child, root, null);
}
}
else
{
IList list = (IList)prop.GetValue(root, null);
foreach (object child in list)
{
if (child == null) continue;
foreach (PropertyInfo childProp in propsToSet)
{
childProp.SetValue(child, root, null);
}
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.