我有一个 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/