使用Reflection在C#中设置嵌套值

时间:2015-12-01 01:32:16

标签: c#

我有一个名为Article的类,它使用另一个名为ZoneStock的类。 此ZoneStock类具有整数ID。

我想使用反射修改它,但它不起作用。

我在Stack Overflow上找到了一些例子,但我没有设法让它工作。

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         //do things
     }
  }.start();

2 个答案:

答案 0 :(得分:1)

我找到了解决问题的方法,现在是:

[HttpPost]
    [ValidateAntiForgeryToken]
    public string Edit(int Id, string Key, string Value)
    {
        Article Article = Db.ArticleById(Id);

        if (Key.Contains(".")) //Property is a custom class
        {
            string[] Keys = Key.Split('.');

            PropertyInfo prop = Article.GetType().GetProperty(Keys[0]);
            Type type = prop.PropertyType;

            object propInstance = Db.Object(type, Convert.ToInt32(Value)); // See the code of this method below

            prop.SetValue(Article, propInstance);

            Db.Update(ref Article);
        }
        else // Property is a simple type: string, int, double, dattime etc.
        {
            PropertyInfo prop = Article.GetType().GetProperty(Key);
            prop.SetValue(Article, Convert.ChangeType(Value, prop.PropertyType), null);
            Db.Update(ref Article);
        }
        Db.Save();

        return Value;
    }

 public static object Object(Type type, int Id)
    {
        object Obj = Ctx.Set(type).Find(Id); //Ctx is may entityFramework Context
        return Obj;
    }

答案 1 :(得分:0)

您似乎收到了错误消息,例如"对象与目标类型不匹配"因为您直接将参数中的值分配给类型(Lvl1)而不是类型的实例。类似下面的代码应该直接分配。

var newValue = Convert.ChangeType(Value, Lvl2.PropertyType);
Lvl2.SetValue(Lvl1.GetValue(Article), newValue);

从评论

更新基于新要求

如果level 1属性可能为null,则下面的代码将实例化属性类型的实例。

// Article.ZoneStack is null
if (Lvl1.GetValue(Article) == null)
    Lvl1.SetValue(Article, Activator.CreateInstance(Lvl1.PropertyType));
// Article.ZoneStack now has a new instance of ZoneStack assigned
var newValue = Convert.ChangeType(Value, Lvl2.PropertyType);
Lvl2.SetValue(Lvl1.GetValue(Article), newValue);
// Article.ZoneStack.Id == newValue