C#泛型、反射-根据对象名获取该类型以及其属性

    //获取名为"MyClass"的类型   
    Type t = Type.GetType("MyClass");   
    //获取"MyClass"的属性   
    PropertyInfo[] properts = t.GetProperties();   
    //根据属性名获取某一属性   
    PropertyInfo p = t.GetProperty("Id");   
    //设置某一属性的值   
    MyClass my = new MyClass();   
    t.setValue(my, 123, null);  

应用:

    public class BaseClass   
            where T : class, new()   
    {   
            public T Test()   
            {   
                    T t = new T();   
                    PropertyInfo[] properts = t.GetType().GetProperties();   
                    foreach(var item in properts)   
                    {   
                            item.setValue(t, objValue, null);   
                    }   
                    return t;   
            }   
    } 

posted @ 2011-11-09 14:32  Byrd  阅读(3032)  评论(0编辑  收藏  举报