[英]How to dynamically create object from collection based on custom attribute?
我必須基於自定義屬性從對象集合創建動態對象。
public class Customer
{
[AccountAttribute(name: "CustomerAccountID")]
public int CustomerID { get; set; }
[RoleAttribute(name: "RoleUserID")]
[AccountAttribute(name: "AccountRole")]
public int RoleID { get; set; }
}
我有一個客戶數據列表
var custData = GetCustomerData();
我想基於該屬性過濾客戶集合。
如果我基於AccountAttribute進行過濾,則我希望有CustomerID和RoleID的列表,並且在新創建的列表中,屬性名稱應為CustomerAccountID,AccountRole。
如果基於RoleAttribute進行過濾,則僅需要RoleID,並且字段名稱應為RoleUserID。
上面的類只是一個示例,有20多個字段可用,並具有三個不同的屬性。
有些字段屬於單個屬性,但有些屬於多個。
當您在編譯時不知道屬性名稱時,創建動態對象的最佳方法是ExpandoObject
它使您可以使用IDictionary<string, object>
接口訪問該對象,因此您所要做的就是添加適當的鍵-值對:
private static dynamic CustomerToCustomObject<TAttribute>(Customer customer)
where TAttribute : BaseAttribute // assuming the Name property is on a base class for all attributes
{
dynamic result = new ExpandoObject();
var dictionary = (IDictionary<string, object>)result;
var propertiesToInclude = typeof(Customer).GetProperties()
.Where(property => property.GetCustomAttributes(typeof(TAttribute), false).Any());
foreach (var property in propertiesToInclude)
{
var attribute = (BaseAttribute)(property.GetCustomAttributes(typeof(TAttribute), false).Single());
dictionary.Add(attribute.Name, property.GetValue(customer));
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.