Skip to main content
 首页 » 编程设计

c#之使用变量名访问子对象

2024年02月13日14bhlsheji

我有一个从数据库中检索的对象 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; } 
    } 
} 

这可以通过使用代码生成更快地完成。您有多种选择,例如:

  1. 对 XmlLog 类型使用反射并生成将与您的应用程序一起编译的 C# 代码。
  2. 使用Reflection构建一个设置XmlLog属性的Expression,然后在运行时将其编译成Func或Action。