我怎样才能找到我的propertyinfo类型?

时间:2011-10-14 11:50:03

标签: c# .net reflection

我有以下代码:

 public class EntityBase
{


 public virtual void Freez(EntityBase obj)
 {
    //TO DO

 }

我的示例中的任何类都继承自EntityBase;像这样:

  public class Person:EntityBase
    {
       public Person()
       {
           this.PersonAsset = new Asset { Title = "asset1" };
       }
        public string Name { get; set; }
       public Asset PersonAsset{get;set;}


    }
   public class Asset : EntityBase
   {
       public string Title { get; set; }
   }

我想当我调用person.Freez()时,如果person有一个属性是PersonAsset这样的类,PersonAsset Freez()方法引发; 我想我必须在EntityBase Freez()方法中使用反射。但是当我得到PersonAsset属性时 通过反射我怎样才能提高它的Freez()方法?或者我如何才能找到我的属性是一个类?

1 个答案:

答案 0 :(得分:1)

public virtual void Freez()
{
    foreach (var prop in this.GetType().GetProperties())
    {
        if (prop.PropertyType.IsClass && typeof(EntityBase).IsAssignableFrom(prop.PropertyType))
        {
            var value = (EntityBase) prop.GetValue(this, null);
            value.Freez();
        }

        if (typeof(ICollection).IsAssignableFrom(prop.PropertyType))
        {
            var collection = (ICollection)prop.GetValue(this, null);
            if (collection != null)
            {
                foreach (var obj in collection)
                {
                    if (obj is EntityBase)
                    {
                        ((EntityBase)obj).Freez();
                    }
                }
            }
        }
    }
}