要在运行时在类中创建动态属性,您可以使用字典来存储属性名称和值。考虑以下代码:
Dictionary<string, object> properties = new Dictionary<string, object>();
该字典可用于定义类的动态属性。例如,要添加名为“test”且值为 100 的动态属性,您可以编写:
properties["test"] = 100;
创建动态属性后,您可以还可以为您的对象添加排序和过滤功能。下面是使用 LINQ 进行过滤的示例:
var filtered = from obj in objects where (int)obj["test"] >= 150 select obj;
这是使用自定义比较器进行排序的示例:
Comparer<int> c = new Comparer<int>("test"); objects.Sort(c);
以下完整内容代码示例演示了 C# 中动态属性的创建、修改、排序和过滤:
using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class ObjectWithProperties { Dictionary<string, object> properties = new Dictionary<string, object>(); public object this[string name] { get { if (properties.ContainsKey(name)) { return properties[name]; } return null; } set { properties[name] = value; } } } class Comparer: IComparer where T : IComparable { string m_attributeName; public Comparer(string attributeName) { m_attributeName = attributeName; } public int Compare(ObjectWithProperties x, ObjectWithProperties y) { return ((T)x[m_attributeName]).CompareTo((T)y[m_attributeName]); } } class Program { static void Main(string[] args) { // create some objects and fill a list var obj1 = new ObjectWithProperties(); obj1["test"] = 100; var obj2 = new ObjectWithProperties(); obj2["test"] = 200; var obj3 = new ObjectWithProperties(); obj3["test"] = 150; var objects = new List (new ObjectWithProperties[] { obj1, obj2, obj3 }); // filtering: Console.WriteLine("Filtering:"); var filtered = from obj in objects where (int)obj["test"] >= 150 select obj; foreach (var obj in filtered) { Console.WriteLine(obj["test"]); } // sorting: Console.WriteLine("Sorting:"); Comparer c = new Comparer ("test"); objects.Sort(c); foreach (var obj in objects) { Console.WriteLine(obj["test"]); } } } }
以上是如何在运行时在 C# 中创建、排序和过滤动态属性?的详细内容。更多信息请关注PHP中文网其他相关文章!