寻找一个.NET ObjectReflector,它将帮助我简化反射对象

时间:2009-09-08 09:15:06

标签: c# .net reflection

我有一个接收来自其他未知模块的对象的类,因此我必须对该对象进行反射以获取其数据,调用其方法等。

为了简化代码以反映对象,我正在构建这个类:

using System;

namespace ApplicationCore.Helpers
{
    class ObjectReflector
    {
        public object TheObject { get; set; }
        public Type TheType { get; set; }

        public ObjectReflector(object theObject)
        {
            TheObject = theObject;
            TheType = theObject.GetType();
        }

        public string GetObjectShortName()
        {
            return TheObject.GetType().Name;
        }

        public string GetObjectLongName()
        {
            return TheObject.GetType().ToString();
        }

        public T GetPropertyValue<T>(string propertyName)
        {
            return (T)TheType.GetProperty(propertyName).GetValue(TheObject, null);
        }

        public T GetMethodValue<T>(string methodName, object[] parameters)
        {
            return (T)TheType.GetMethod(methodName).Invoke(TheObject, parameters);
        }

    }
}

所以我有一个漂亮,干净的代码,如下所示:

namespace ApplicationCore.Presenters
{
    public class SmartFormPresenter
    {
        public UserControl View { get; set; }

        public string ShortName { get; set; }
        public string LongName { get; set; }
        public string FirstName { get; set; }
        public int Age { get; set; }
        public int AgePlusTwo { get; set; }

        public SmartFormPresenter(object o)
        {
            SmartFormView smartFormView = new SmartFormView();
            View = smartFormView;
            smartFormView.DataContext = this;

            ObjectReflector or = new ObjectReflector(o);
            ShortName = or.GetObjectShortName();
            LongName = or.GetObjectLongName();
            FirstName = or.GetPropertyValue<string>("FirstName");
            Age = or.GetPropertyValue<int>("Age");
            AgePlusTwo = or.GetMethodValue<int>("GetAgeInTwoYears", null);
        }
    }
}

但现在我需要制作方法,例如读出不是 int 而是 List<Contract> ,这样我就得获得List<object>然后反思“对象” “等等。

所以我认为这是以前完成的。 .NET中是否有任何类型的工具或类,称为ObjectReflector,它可以帮助我简化对象的反射,就像我上面做的那样?

1 个答案:

答案 0 :(得分:0)

无法在我的评论中发布代码。这可以帮助您入门:

foreach (PropertyInfo pi in oProps)
           {
                Type colType = pi.PropertyType;

                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()      
                ==typeof(Nullable<>)))
                 {
                     colType = colType.GetGenericArguments()[0];
                 }