c# - 在现有类 c# 中在运行时动态添加属性

标签 c# .net windows reflection reflection.emit

我有一个 UI,从中我们可以在表字段中添加以下值

  • 产品名称
  • 产品编号
  • 产品编号

  • 我有一个具有一些现有属性的现有类 Product
    public class Product
    {
        public string ProductID { get; set; }
        //product in a product search listing
        public string StoreName { get; set; }
        public string SearchToken { get; set; }
    
    }
    

    我正在寻找一种方法,当用户在表字段中添加值时,该方法将在运行时(动态)在现有类 Product 中添加属性

    最佳答案

    我不知道在运行时定义属性的方法,但另一种实现所需的方法是在 C# 中使用动态对象 ExpandoObject .

    您首先需要声明您的动态对象,它在内部使用一种字典,以便您可以向其中添加属性。

    using System.Dynamic;
    dynamic newobj = new ExpandoObject();
    
    //I can add properties during compile time such as this
    newobj.Test = "Yes";
    newobj.JValue = 123;
    
    //Or during runtime such as this (populated from two text boxes)
    AddProperty(newobj, tbName.Text, tbValue.Text);
    
    public void AddProperty(ExpandoObject expando, string name, object value)
    {
        var exDict = expando as IDictionary<string, object>;
        if (exDict.ContainsKey(propertyName))
            exDict[propertyName] = propertyValue;
        else
        exDict.Add(propertyName, propertyValue);
    }
    

    我在这里的解决方案中使用过一次:Flattern child/parent data with unknown number of columns

    但是这些来源可能可以更好地解释它;
    https://www.oreilly.com/learning/building-c-objects-dynamically

    https://weblog.west-wind.com/posts/2012/feb/08/creating-a-dynamic-extensible-c-expando-object

    https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/types/using-type-dynamic

    但是,我不确定与使用简单的 Dictionary<string, object> 相比,这是否真的能为您提供任何真正的优势。

    关于c# - 在现有类 c# 中在运行时动态添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44067241/

    相关文章:

    C# 如何连接到 MS Access 2007

    .net - 如何在 Excel 中将区域设置应用于十进制格式?

    c# - 连续检查 Queue<T>

    windows - cabal 安装 glib 出错

    mysql - 数据库服务器配置

    c# - 哪个 DLL 包含 Microsoft.Powershell.Command 命名空间下的异常?

    c# - Brushes.White 使图形演示变慢

    javascript - 在查询字符串处传递 '+'

    c# - Quartz.net 取消 token

    python - Postgres - 如何在 Windows 上使用 psql 从 Python 执行多行查询?