简体   繁体   English

在其他语言的“块值”的C#中等效

[英]Equivalent in C# of “Block values” in other languages

In some languages, almost everything can be used as a value. 在某些语言中,几乎所有东西都可以用作价值。 For example, some languages let you treat a block of code as a unit which can return a value. 例如,某些语言允许您将代码块视为可以返回值的单元。

In Scheme, a block of code wrapped in a let can return a value: 在Scheme中,包含在let的代码块可以返回一个值:

(define val
  (let ()
    (define a 10)
    (define b 20)
    (define c (+ a b))
    c))

Perl 5 also supports blocks as values: Perl 5还支持块作为值:

my $val = do
{
    my $a = 100;
    my $b = 200;
    my $c = $a + $b;
    $c;
};

The closest approximation to block values I could come up with in C# was to use a lambda that is cast and immediately called: 我在C#中可以提出的块值的最接近的近似值是使用一个被转换的lambda并立即调用:

var val = ((Func<int>)(() =>
{
    var a = 10;
    var b = 20;
    var c = a + b;
    return c;
}))();

That's not too bad and is in fact exactly what is happening semantically with Scheme; 这不是太糟糕,实际上正是在语义上与Scheme发生的事情; the let is transformed to a lambda which is applied. let被转换为应用的lambda It's at this point that I wouldn't mind macros in C# to clean up the syntactic clutter. 在这一点上,我不介意用C#中的宏来清理语法杂乱。

Is there an another way to get "block values" in C#? 是否有另一种方法可以在C#中获得“块值”?

Sorry, at first I seemed to have misread your question, but it seems delegates (as in your question) are exactly what you are looking for no? 对不起,起初我似乎误解了你的问题,但似乎代表 (如你的问题)正是你正在寻找的没有? If you are interested in quickly grouping a set of different values together, and not necessarily logic, my previous answer still applies. 如果您有兴趣快速将一组不同的值组合在一起,而不一定是逻辑,我之前的答案仍然适用。


C# supports anonymous types . C#支持匿名类型

var v = new { Amount = 108, Message = "Hello" };

The var keyword is introduced so you don't have to specify a type name. 引入了var关键字,因此您不必指定类型名称。

Afterwards you can access the members as follows: 之后您可以按如下方式访问成员:

Console.WriteLine( v.Amount );

Another solution since C# 4.0 is using Tuples which basically group a set of unnamed values together. 自C#4.0以来的另一个解决方案是使用Tuples ,它基本上将一组未命名的值组合在一起。

var population = Tuple.Create(
    "New York", 7891957, 7781984,
    7894862, 7071639, 7322564, 8008278 );

You have to access them using population.Item1 , population.Item2 , ... 你必须使用population.Item1population.Item2 ,...来访问它们

In some languages, almost everything can be used as a value. 在某些语言中,几乎所有东西都可以用作价值。

You give 1 example, Scheme. 举一个例子,Scheme。 Scheme is a functional language, (almost) everything in Scheme is a function rather than a value. Scheme是一种函数式语言,(几乎)Scheme中的所有东西都是函数而不是值。

C# is now partially a functional language through the inclusion of Linq. 通过包含Linq,C#现在已成为部分功能语言。

So the equivalents you seek are Linq queries and indeed lambda functions. 所以你寻找的等价物是Linq查询和lambda函数。 If that's not enough, take a look at F#. 如果这还不够,请看一下F#。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM