【问题标题】:Unknown operator in c# [duplicate]c#中的未知运算符[重复]
【发布时间】:2016-07-02 10:43:29
【问题描述】:

您好,我不是 C# 专家,我发现了这段代码,但并不真正理解它的作用。

我以前从未在 c# 中见过运算符 =>。就像重定向?

public byte[] methodA(byte[] data) => 
  this.methodB(data);

【问题讨论】:

  • 不,是 lambda 表达式。你可以在这里阅读msdn.microsoft.com/library/bb397687.aspx
  • @S.Nadezhnyy:不,不是这种情况。
  • 尽管=>(也)从 lambda 表达式中已知,但这不是 lambda 表达式。
  • 其实看起来更像是c#6表达式体方法
  • Related question 用于属性而不是方法。

标签: c#


【解决方案1】:

这称为表达式体方法。这是 C# 6.0 中的新功能。

相当于:

public byte[] methodA(byte[] data) {
  return this.methodB(data);
}

【讨论】:

  • 除了答案,这里是MSDN page的链接。只需滚动到Expression Bodied Functions and Properties 部分。
【解决方案2】:

这是 C#6.0 中名为“Expression Bodied function”的新功能,它也可以减少您的代码行数。 例如

 //Old way
        public string Name
        {
            get
            {
                return "David";
            }
        }
//New way
        public string Name => "David";

//old way 
        public Address GetAddressByCustomerId(int customerId)
        {
            return AddressRepository.GetAddressByCustomerId(customerId);
        }
//New Way
        public Address GetAddressByCustomerId(int customerId) => 
               AddressRepository.GetAddressByCustomerId(customerId);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    相关资源
    最近更新 更多