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

标签 c# forms

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

关于c# - 使用变量名访问子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459502/

相关文章:

c# - 来自 NAudio 的原始音频

c# - HighChart xAxis 日期时间值

php - Symfony2 形式转 JSON 结构

.net - 在绑定(bind)之前使用 MVC ModelBinders 过滤帖子值

javascript - 如何使我的错误发布在我的保留部分中?

c# - 在基类中激活未触发?

c# - 将整数发送到 Android 后台应用程序

C# 对 XElement 进行排序,带注释

forms - 类型 'http' 上不存在属性 'Component',Angular 2

ios - IBTool 无法通过 Xcode 9.2 iOS 11.3