c# - c# Attribute 辅助方法的泛型
问题描述
我找不到在 .Net Core 中制作这个 DRY 的好方法。(不要重复自己)。我怎样才能做到这一点,这样我就不会重复大部分逻辑?以下是2种方法:
public static string GetCategory(this Enum val)
{
CategoryAttribute[] attributes = (CategoryAttribute[])val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(CategoryAttribute), false);
return attributes.Length > 0 ? attributes[0].Category : string.Empty;
}
public static string GetDescription(this Enum val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
解决方案
我会从这个开始:
public static T GetAttribute<T>(this Enum val)
where T : Attribute
{
return (T)val
.GetType()
.GetField(val.ToString())
.GetCustomAttribute(typeof(T), false);
}
这将您的方法变成了这样:
public static string GetCategory(this Enum val)
{
return val.GetAttribute<CategoryAttribute>()?.Category ?? string.Empty;
}
public static string GetDescription(this Enum val)
{
return val.GetAttribute<DescriptionAttribute>()?.Description ?? string.Empty;
}
可以说您可以做更多的事情来使这些最终方法更加干燥,但我猜您在这里使用的模式(从属性获取属性并返回其值或空字符串)可能不够常见值得为此专门创建一种方法。另一方面,该GetAttribute
方法可能更可重用。
推荐阅读
- php - 如何解决 Laravel 中的“Access-Control-Allow-Origin”问题?
- spring - 在 Spring Boot @Transactional 类中,如何在两次提交之间更改 Hibernate DAO 对象后执行对不同存储库的提交?
- c++ - 运行 QPropertyAnimation 后 QWiget 的奇怪行为
- c# - 从数据表更新excel表列时需要避免数据表中5k条记录的延迟
- android-studio - 防止 Android Studio 检查将 Java 流链标记为包含可能的 NullPointerException
- java - 无法使用 OAuth2.0 将额外参数传递给 Spring-Security
- javascript - JavaScript - 数组,对象 - 如何简化此代码
- python - 视图 students.views.addgrregister 没有返回 HttpResponse 对象。它返回 None 而不是
- sql - 将 SQL 模型复制到 Ruby on Rails postgresql 模型中
- mule - 在tomcat 7服务器中的mule应用程序中处理请求时出错