首页 > 解决方案 > 对象属性上的自定义扩展方法以返回 DefaultValue

问题描述

我想创建一个自定义扩展,该扩展将适用于 object 的属性T,而不管属性的类型如何。我需要扩展来获取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; }
}

标签: c#.netextension-methods

解决方案


您需要使用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);   

推荐阅读