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:
(define val
(let ()
(define a 10)
(define b 20)
(define c (+ a b))
c))
Perl 5 also supports blocks as values:
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:
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; the let
is transformed to a lambda
which is applied. It's at this point that I wouldn't mind macros in C# to clean up the syntactic clutter.
Is there an another way to get "block values" in 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 .
var v = new { Amount = 108, Message = "Hello" };
The var
keyword is introduced so you don't have to specify a type name.
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.
var population = Tuple.Create(
"New York", 7891957, 7781984,
7894862, 7071639, 7322564, 8008278 );
You have to access them using population.Item1
, population.Item2
, ...
In some languages, almost everything can be used as a value.
You give 1 example, Scheme. Scheme is a functional language, (almost) everything in Scheme is a function rather than a value.
C# is now partially a functional language through the inclusion of Linq.
So the equivalents you seek are Linq queries and indeed lambda functions. If that's not enough, take a look at F#.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.