问题一:设计一个方法,传如一个对象,在屏幕上打印出这个对象所有的属性名称和属性值public void PrintObjectProperty( object obj )如传如一个string对象PrintObjectProperty("12345")屏幕上就会打印Length : 5请问如何实现?问题二:传入任意对象,如果该对象有名称为Save的无参数无返回值的方法,就调用这个方法,这个程序如何设计?

解决方案 »

  1.   

    using System;
    using System.Reflection;
    using System.Windows.Forms;namespace Learn
    {
    /// <summary>
    /// ExcieseReflaction 的摘要说明。
    /// </summary>
    public class ExcieseReflection
    {
    private string _strValue="string test";
    protected int _intValue = 5;
    public DateTime _datNow = System.DateTime.Now;
    public Users _objUser = new Users("001","Vicky");

    private string strValue
    {
    get{return _strValue;}
    } public Users objUser
    {
    get{return _objUser;}
    } //执行这个方法
    public static void Exec()
    {
    ExcieseReflection c = new ExcieseReflection(); GetProperties(c);
    } public static void GetProperties(object o)
    {
    Type t=o.GetType();
    PropertyInfo[] f = t.GetProperties(BindingFlags.Public|BindingFlags.Instance|BindingFlags.NonPublic);
    foreach(PropertyInfo f1 in f)
    {
    object objValue = f1.GetValue(o,null);
    if (f1.PropertyType.IsClass  && !(objValue is String))
    GetProperties(objValue);
    else
    MessageBox.Show(f1.Name+" = "+objValue.ToString());
    }
    }
    public class Users
    {
    private string userid;
    private string username; private string UserID
    {
    get{return userid;}
    } private string UserName
    {
    get{return username;}
    } public Users(string id,string name)
    {
    this.userid=id;
    this.username=name;
    }
    }
    }
    }
      

  2.   

    假设另一个工程中的所有类都编译到一个dll文件中了,在这很多的类当中,有一个类叫StringUtil,名称空间在HSMP.CommonBasic.Common下
    该类中有一个方法:
    public double GetSum(double x,double y)
    {
    return x+y;
    }
    编译后dll文件的存放路径是:D:\Test\HSMP.CommonBasic.dll
    现在的问题是,如何通过程序调用该dll文件中的GetSum方法
    大概有以下几步:
    using System.Reflection;
    A.
    //这里要用LoadFrom,只有在本工程里添加了该dll的引用后才可以使用Load
    Assembly objAss = Assembly.LoadFrom(@"D:\Test\HSMP.CommonBasic.dll");
    //HSMP.CommonBasic.Common.StringUtil类的全路径
    Type t=objAss.GetType("HSMP.CommonBasic.Common.StringUtil"); 
    //动态生成类StringUtil的实例
    object obj=System.Activator.CreateInstance(t);
    //参数信息,GetSum需要两个int参数,如果方法没有参数,就声明一个长度为0的数组
    System.Type[] paramTypes = new System.Type[2];
    paramTypes[0] = System.Type.GetType("System.Int32");
    paramTypes[1] = System.Type.GetType("System.Int32");
    //找到对应的方法
    MethodInfo p = t.GetMethod("SayHello", paramTypes)
    //参数值,如果所调用的方法没有参数,不用写这些
    Object[] parameters = new Object[2];
    parameters[0] = 3;
    parameters[1] = 4;
    object objRetval = p.Invoke(obj, parameters); //如果没有参数,写null即可。
    //objRetval即为返回的值