[英]Custom Extension Method on object properties to return DefaultValue
我想創建一個自定義擴展,它可以處理對象T
的屬性,而不管屬性的類型如何。 我需要擴展來獲取DefaultValue
屬性的DefaultValue
。
看看下面的類,我希望能夠做這樣的事情:
Employee employee = new Employee();
string defaultNationality = employee.employeeNationality.GetDefaultValue();
其中Employee
被定義為
public class Employee
{
[Browsable(false)]
public int employeeKey { get; set; }
[DisplayName("Name")]
[Category("Design")]
[Description("The name of the employee.")]
public string employeeName { get; set; }
[DisplayName("Active")]
[Category("Settings")]
[Description("Indicates whether the employee is in active service.")]
[DefaultValue(true)]
public bool employeeIsActive { get; set; }
[DisplayName("Nationality")]
[Category("Settings")]
[Description("The nationality of the employee.")]
[DefaultValue("Dutch")]
public string employeeNationality { get; set; }
}
您需要使用GetCustomAttribute
方法來獲取所需的屬性值。 例如,您可以將所需的擴展方法定義為
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
public static class Extensions
{
public static T GetDefaultValue<S,T>(this S source,Expression<Func<S,T>> expression)
{
var body = expression.Body as MemberExpression;
if(body.Member.GetCustomAttributes<DefaultValueAttribute>().Any())
{
return (T)body.Member.GetCustomAttribute<DefaultValueAttribute>().Value;
}
return default;
}
}
如果找不到所需的屬性(在本例中為DefaultValueAttribute
),您可以返回該類型的默認值(或根據您的用例拋出異常)。
用法如下
string defaultNationality = employee.GetDefaultValue(x => x.employeeNationality);
您可以使用這樣的擴展方法:
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
public static class ObjectExtensions
{
public static K GetDefaultValue<T, K>(this T obj, Expression<Func<T, K>> exp)
{
var info = ((MemberExpression)exp.Body).Member;
return (K)(TypeDescriptor.GetProperties(info.DeclaringType)[info.Name]
.Attributes.OfType<DefaultValueAttribute>()
.FirstOrDefault()?.Value ?? default(K));
}
}
並像這樣使用它:
var deualtValue = someObject.GetDefaultValue(x=>x.SomeProperty);
筆記
該方法嘗試根據DefaultValue
屬性獲取屬性的默認值,如果該屬性沒有這樣的屬性,則返回該屬性類型的默認值,例如對於整數屬性,如果不能找到DefaultValue
屬性,它返回 0。
為了獲取屬性和元數據,我通常使用TypeDescriptor
因為它更靈活,但是使用 Reflection 也是完全有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.