如何取得這些參數
代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace getPropTest
{
public class dologin
{
public static RootObject rootObject = new RootObject();
public class RootObject
{
public string param { get; set; }
}
public void exec()
{
rootObject.param = "New_param";
}
}
class Program
{
public static object getObject(string className)
{
Assembly assembly = Assembly.GetExecutingAssembly();
assembly.GetTypes();
object obj = assembly.CreateInstance("getPropTest." + className);
return obj;
}
public static bool execMethod(object obj, string methodName)
{
try
{
Type type = obj.GetType();
MethodInfo methodinfo = type.GetMethod(methodName);
methodinfo.Invoke(obj, null);
return true;
}
catch (Exception ex)
{
return false;
}
}
public static void getProperties(object obj, string memberName)
{
Type type = obj.GetType();
if (memberName == "RootObject")
{
MemberInfo[] memberInfo = type.GetMember("rootObject");
object sub_obj = memberInfo.GetValue(0);
Console.WriteLine(sub_obj.ToString());//RootObject rootObject
/*
* 如何獲取rootObject下的所有屬性,比如此處的param = "New_param"???
*/
}
}
static void Main(string[] args)
{
object obj = getObject("dologin");
execMethod(obj, "exec");
getProperties(obj, "RootObject");
}
}
}
已解決
public static void getProperties(object obj, string memberName)
{
Type type = obj.GetType();
FieldInfo field = null;
if (memberName == "RootObject")
{
field = type.GetField("rootObject");
}
object _obj = field.GetValue(obj);
Type _type = _obj.GetType();
foreach (PropertyInfo propertyInfo in _type.GetProperties())
{
Console.WriteLine("{0}: {1}", propertyInfo.Name, propertyInfo.GetValue(_obj, null));
}
}