【发布时间】:2020-08-10 20:44:47
【问题描述】:
我有这个扩展方法可以在c#中获取枚举的属性。
public static TAttribute ToAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute =>
value.GetType()
.GetField(Enum.GetName(value.GetType(), value))
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
如您所见,我需要执行两次value.GetType(这不是有效的)。我也知道我可以删除 lambda 表达式并像以前那样做:
public static TAttribute ToAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var type = value.GetType();
return type
.GetField(Enum.GetName(type, value))
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
}
但是有没有办法在这样的一行表达式中重用value.getType 的结果?也许是我不知道的 c# 中的一个关键字?
我正在寻找这样的东西:
public static TAttribute ToAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute =>
value.GetType()
.GetField(Enum.GetName(this, value))
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
【问题讨论】:
-
看看这里。这可能会帮助stackoverflow.com/questions/5397027/…
-
简短回答:不,不可能!如果您的担忧与性能有关,它不会减慢您的代码速度。 (性能差异以纳秒为单位)
-
好吧,即使异步执行相同的代码数百万次似乎也没有性能问题。如果担心代码可读性怎么办?
-
或者代码质量怎么样?
-
如果担心可读性或质量,请使用第二个示例。