What does => operator pointing from field or a met

2019-02-15 12:53发布

问题:

This question already has an answer here:

  • What does “=>” do in .Net C# when declaring a property? [duplicate] 2 answers

I've seen an operator => used in the following example:

public int Calculate(int x) => DoSomething(x);

or

public void DoSoething() => SomeOtherMethod();

I have never seen this operator used like this before except in lamba expressions.

What does the following do? Where, when should this be used?

回答1:

These are Expression Body statements, introduced with C# 6. The point is using lambda-like syntax to single-line simple properties and methods. The above statements expand thusly;

public int Calculate(int x)
{
    return DoSomething(x);
}

public void DoSoething()
{
    SomeOtherMethod();
}

Notably, properties also accept expression bodies in order to create simple get-only properties:

public int Random => 5;

Is equivalent to

public int Random
{
    get
    {
        return 5;
    }
}


回答2:

Take a look at this Microsoft Article. It's a C# 6.0 feature where properties have no statement body. You could use them to get methods, or single line expressions. For example:

public override string ToString() => string.Format("{0}, {1}", First, Second);


回答3:

It's a new shorthand syntax in C# 6.

In your first example it's defining a public method, Calculate(int x) whose implementation is defined within DoSomething(x).

An equivalent definition would be:

class SomeClass {

    public int Calculate(int x) { return DoSomething(x); }

    protected int DoSomething(int x) { ... }
}


回答4:

A new feature in C# 6.0 called an expression body.

It is shorthand to write a single line of code with a return value.

For example

int GetNumber() => 1;

Is an expression body statement which is the same as:

int GetNumber()
{
    return 1;
}

You can read more here