c# - 对象属性上的自定义扩展方法以返回 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; }
}
解决方案
您需要使用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);
推荐阅读
- javascript - 脚本不改变文本
- java - 包含多个斜杠的 Spring Boot 路径变量
- r - 不引用块标签时是否有任何缺点?
- spring-integration - 具有基本身份验证的 Spring Integration 出站网关
- javascript - 如何访问“this.props.match.params”以及其他道具?
- java - onDestroy后的android Fragment重新创建 - FragmentManagerState ClassNotFound
- database - YugaByte DB 支持什么样的访问控制机制?
- hyperledger-fabric - 从链码 [Fabric 1.2 或 1.3] 中识别执行链码的 Peer/Org
- c# - 阅读 appsettings.json - 字段保持为空
- dynamics-nav-2013 - 如何使用或过滤