通过直接字符串引用将值传递给实体

JBn*_*tis 2 c# asp.net-mvc

我知道这听起来有点模糊,所以提供编码解释.

可以说我有一个实体:

   public class Times
    {
        public int TimesId { get; set; }
        public int DateRange { get; set; }
        public String Days { get; set; }

    }
Run Code Online (Sandbox Code Playgroud)

以及返回值的操作.我想根据传递给操作的"name"值在我的实体内部设置一个属性:

public JsonResult SaveValues(string name, int value)
{
    //lets say: name = "TimesId" 

    times t = new times;
    // t.name = should refer to t.TimesId and used to insert values like t.TimesId
    t.name = value; // what I'm trying to acheive
}
Run Code Online (Sandbox Code Playgroud)

是否可以直接进行此类参考?

mat*_*mmo 6

通过反射,可以做到:

Times t = new Times();
typeof(Times).GetProperty(name).SetValue(t, value);
Run Code Online (Sandbox Code Playgroud)

但实际上,你是不是只是把你SaveValuesTimes对象作为参数?然后你可以自己填写并保存反射.