【问题标题】:How can I reuse the result of an expression variable in a lambda operator in c#?如何在 c# 的 lambda 运算符中重用表达式变量的结果?
【发布时间】: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/…
  • 简短回答:不,不可能!如果您的担忧与性能有关,它不会减慢您的代码速度。 (性能差异以纳秒为单位)
  • 好吧,即使异步执行相同的代码数百万次似乎也没有性能问题。如果担心代码可读性怎么办?
  • 或者代码质量怎么样?
  • 如果担心可读性或质量,请使用第二个示例。

标签: c# .net


【解决方案1】:

没有重用函数返回值的语法(当然除了分配变量)。但是如果你想避免调用GetType() 两次,你可以重写这个特定的表达式:

public static TAttribute ToAttribute<TAttribute>(this Enum value)
    where TAttribute : Attribute =>
        value.GetType()
             .GetField(value.ToString())
             .GetCustomAttributes(false)
             .OfType<TAttribute>()
             .SingleOrDefault();

【讨论】:

  • Enum.GetName(value.GetType(), value)value.ToString() 一样吗?
猜你喜欢
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 2014-02-20
  • 2011-09-16
  • 2016-06-14
  • 1970-01-01
相关资源
最近更新 更多