我有一个从数据库中检索的对象 XMLLog。表单允许用户编辑对象中的字段,但由于复杂的原因,我无法返回修改后的对象,我在帖子中返回键列表。
我想做以下事情:
//get XMLLog from the database
foreach (var key in Request.Form.AllKeys)
{
XMLLog.key = Request.Form[key];
}
//write XMLLog back to the Database
如果没有一个巨大的 case 语句来测试每个可能的键,有什么方法可以实现这一点?
最佳答案
你可以使用反射来做到这一点,但它会很慢。下面是一个演示原理的小程序(编译运行即可):
using System;
using System.Collections.Generic;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var log = new XmlLog();
var values = new Dictionary<string, string> { { "Hello", "1" }, { "World", "2" } };
foreach (var methodInfo in typeof(XmlLog).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
methodInfo.SetValue(log, values[methodInfo.Name]);
}
Console.WriteLine(log.Hello);
Console.WriteLine(log.World);
}
class XmlLog
{
public string Hello { get; set; }
public string World { get; set; }
}
}
这可以通过使用代码生成更快地完成。您有多种选择,例如:
- 对 XmlLog 类型使用反射并生成将与您的应用程序一起编译的 C# 代码。
- 使用Reflection构建一个设置XmlLog属性的Expression,然后在运行时将其编译成Func或Action。
关于c# - 使用变量名访问子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459502/