c# - 获取枚举实例给定它的自定义属性的值
问题描述
最近,我尝试使用谷歌搜索并寻找答案,如何获得枚举值具有自定义属性的枚举实例。我开始输入其自定义属性的值,我想知道哪个枚举值对应。
例子:
public enum whatever
{
[MyCustomAttribute("foo1", "foo2")]
SOMETHING,
[MyCustomAttribute("foo2", "foo3")]
SOMETHING_2
}
... 属性:
public MyCustomAttribute() : Attribute
{
string somevalue;
string anothervalue;
public MyCustomAttribute(string f, string f2)
{
somevalue = f;
anothervalue = f2;
}
}
我得到“foo1”作为输入,我想返回whatever.SOMETHING。
解决方案
我能够想出一个非常适合我的简单解决方案,我很惊讶我无法在任何地方找到它。
public whatever GetWhatever(string value)
=> typeof(whatever).GetEnumValues()
.Cast<whatever>().First(val => val .GetCustomAttributeee<MyCustomAttribute>().somevalue == value);
如果你能给我一些关于我的解决方案及其问题的反馈,我会很高兴。
推荐阅读
- java - 为什么 Spring Boot 执行器有点分隔的普罗米修斯指标名称?
- python - 使用 sklearn 和 GPFlow 的高斯回归
- powershell - 具有不同权限的Powershell中的不同SSD序列号
- ios - Phonegap 构建错误:Xcode 无法确定配置文件的类型/未找到签名证书“iOS 分发” - Xcode 11 或 Xcode 10.1
- javascript - 刷新列表时挂钩 useCallback 继续使用旧值
- c++ - 分治算法找到最大元素的位置
- r - as.numeric 在有空格时创建 NA
- python - 使用 K-Means 聚类算法时,是否有可能有一组数据导致无限循环?
- vue.js - 为什么 vue-router 不起作用?我的项目在 GitHub
- gitlab - Gitlab 管道描述与预期不匹配