如何反射类库的类文件中的变量并赋值
现在这样写报错:model.fi = stArr1[1];  ConfigModel不具有fi的定义。Models.Payment payment = PaymentManager.GetPaymentByPayId(pid);
        if (payment != null)
        {
            SortedDictionary<string, string> sd = new SortedDictionary<string, string>();
            Com.ConfigModel model = new Com.ConfigModel();
            if (!payment.PayConfig.Equals(string.Empty))
            {
                string[] stArr = payment.PayConfig.Split(',');
                Type type = Com.ConfigModel.GetType();
                foreach (string str in stArr)
                {
                    string[] stArr1 = str.Split(':');
                    FieldInfo fi = type.GetField(stArr1[0]); //stArr1[0]是ConfigModel中的变量名
                    model.fi = stArr1[1]; //stArr1[1]是要赋值
             
                }
            }

解决方案 »

  1.   

    http://msdn.microsoft.com/zh-cn/library/system.reflection.fieldinfo.setvalue(v=vs.100).aspx
      

  2.   

    终于搞定了,把我的代码贴出来分享一下,用到了反射变量名和反射类名。之前一直报错:未将对象引用到实例,看了msdn原来反射get{}set{},要用BindingFlags.NonPublic | BindingFlags.Instance)Models.Payment payment = PaymentManager.GetPaymentByPayId(pid);
            if (payment != null)
            {
                Com.ConfigModel model = new Com.ConfigModel();
                if (!payment.PayConfig.Equals(string.Empty))
                {
                    string[] stArr = payment.PayConfig.Split(',');
                    Type type = model.GetType();
                    foreach (string str in stArr)
                    {
                        string[] stArr1 = str.Split(':');
                        FieldInfo fi = type.GetField(stArr1[0], BindingFlags.NonPublic | BindingFlags.Instance);
                        fi.SetValue(model, stArr1[1]);
                    }
                }            Com.Payment.Base b = (Com.Payment.Base)Assembly.Load("Com").CreateInstance("Com.Payment." + payment.PayCode);
                if (b != null)
                {
                    strPayConfig = b.GetConfig(model);
                }