문제

In Scala I can do something like this:

val result = {
  val a = 4
  val b = 16
  a + b
}

Which is basically just a (in this case immutable) variable that has its own local scoping like a method.

The following expression, however, is completely illegal in C#:

var result = 
{
    var a = 4;
    var b = 16;
    return a + b;
}

So the question is, is there any way I could emulate this feature, without being forced to make a Func or separate method?

도움이 되었습니까?

해결책 2

To avoid result is delegate, you can call Func to run immediately after instantiating:

var result = new Func<int>(() => {
    var a = 4;
    var b = 16;
    return a + b;
})();

다른 팁

My suggestion is:

var result = 0;
{
  var a = 4;
  var b = 16;
  result = a + b;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top