程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> c# object-如何取得這些參數(內含源碼)

c# object-如何取得這些參數(內含源碼)

編輯:編程解疑
如何取得這些參數(內含源碼)

如何取得這些參數
如何取得這些參數

 代碼:
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));
            }
        }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved