如何解决如何在C#中的Lambda运算符中重用表达式变量的结果?
我有这种扩展方法来获取c#中Enum的属性。
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();
解决方法
没有重用函数返回值的语法(当然,除了分配变量外)。但是,如果您想避免两次调用GetType()
,则可以重写以下特定表达式:
public static TAttribute ToAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute =>
value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。