我不知道在运行时定义属性的方法,但实现您需要的另一种可能性是使用 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 propertyName, object propertyValue)
{
var exDict = expando as IDictionary<string, object>;
if (exDict.ContainsKey(propertyName))
exDict[propertyName] = propertyValue;
else
exDict.Add(propertyName, propertyValue);
}
我在这里的解决方案中使用过一次:展平具有未知列数的子/父数据 https://stackoverflow.com/questions/36350480/flattern-child-parent-data-with-unknown-number-of-columns
但这些来源可能可以更好地解释这一点;https://www.oreilly.com/learning/building-c-objects-dynamically 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://weblog.west-wind.com/posts/2012/feb/08/creating-a-dynamic-extensible-c-expando-object
https://learn.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/types/using-type-dynamic https://learn.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/types/using-type-dynamic
但是,我不确定这是否真的会比使用简单的方法给您带来任何真正的优势Dictionary<string, object>