the title is a mouthful and not even sure it's accurate (couldn't make much sense of this ), so I'll try to explain what I'd like to accomplish in C#
by using equivalent javascript
. Any suggestion as to what I should title this question is very much welcome.
In C#
, say I have defined this function:
Func<string, string> getKey = entity => {
switch(entity) {
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
};
string key = getKey(/* "a", "b", or something else */);
Now suppose I don't want to define the getKey
function explicitly, but use it anonymously as I would in this equivalent javascript
snippet:
string key = (function(entity) {
switch(entity) {
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
}(/* "a", "b", or something else */));
How would I go about writing that in C#
? I tried:
string key = (entity => {
switch(entity) {
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
})(/* "a", "b", or something else */);
but I get syntax error CS0149: Method name expected
.
Thanks in advance, cheers.
IMO, the nearest equivalent is this:
var key = new Func<string, string>(entity =>
{
switch (entity)
{
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
})("a");
C# is a compiled language and thus different from javascript in a number of ways. What you are looking for is a closure https://en.wikipedia.org/wiki/Closure_(computer_programming) . And those are possible in C# (for example Linq).
But I think that what you are looking for can be solved nicely with extension methods ( https://msdn.microsoft.com/en-us//library/bb383977.aspx ):
using ExtensionMethods;
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("a".ConvertKey());
}
}
}
namespace ExtensionMethods
{
public static class MyExtensions
{
public static string ConvertKey(this String key)
{
switch (key)
{
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
}
}
}
EDIT: Same program using Linq:
using System;
using System.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new[] { "a" }.Select(entity =>
{
switch (entity)
{
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
}).First());
Console.ReadKey();
}
}
}
You can think of "Select" as "map" in functional terms. Hope this helps!
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.