我知道这听起来有点模糊,所以我提供编码解释。
假设我有一个实体:
public class Times
{
public int TimesId { get; set; }
public int DateRange { get; set; }
public String Days { get; set; }
}
还有一个带有返回值的 Action 。 我想根据传递给操作的“名称”值在我的实体内部设置一个属性:
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
}
是否可以直接做这种引用?
最佳答案
有可能,使用反射,通过做:
Times t = new Times();
typeof(Times).GetProperty(name).SetValue(t, value);
但实际上,让 SaveValues
将 Times
对象作为参数不是更好吗?然后你可以自己填充它并保存反射。
关于c# - 通过直接字符串引用将值传递给实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16440218/