要在執行階段在類別中建立動態屬性,您可以使用字典來儲存屬性名稱和值。考慮以下程式碼:
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中文網其他相關文章!