Hello!
Here is the code:
array( "Param1" => "lastname", "Param2" => array( "Param21" => "name1", "Param22" => "name2", ) )
Question:
What will it look like in C #? Prompt analogue of this operator "=>".
"lastname", "Param2" => array( "Param21" => "name1", "Param22" => ...">
The exact analogue of the operator =>
in this context is {key, value}
when using the Collection Initializer mechanism:
var arr = new Dictionary<string, object> { { "Param1", "lastname" }, { "Param2", new Dictionary<string, object> { { "Param21", "name1" }, { "Param22", "name2" } } } };
Collection Initializer uses duck typing - i.e. it does not require that Dictionary<K, V>
initialized with it. Instead, it simply checks that the object being initialized is IEnumerable
, and that it has an Add
method with two parameters.
The php example tries to mix strings and other arrays in one array, so that in C # the equivalent code will not have strong typing either.
I did not work with PHP, but a quick overview of the answers showed that the =>
operator in PHP is used to create and extract information from associative arrays. The equivalent in C # can be a Dictionary
.
But the example you cited will not work 1 translate directly into C #, since, according to the documentation , any type of object can be used as a value in PHP. Therefore, in order to translate this code to C #, you need to define a common type for representing values ββin a dictionary.
Suppose you implement a kind of JSON representation. Then your code might look like this:
var data = new Dictionary<JsonString, JsonNode> { {new JsonString("Param1"), new JsonString("lastName")}, { new JsonString("Param2"), new JsonObject(new Dictionary<JsonString, JsonNode> { {new JsonString("Param21"), new JsonString("name1")}, {new JsonString("Param22"), new JsonString("name2")} }) } };
Provided that you have defined a class hierarchy where JsonNode
acts as the base JsonString
, and JsonString
and JsonObject
are inherited from it.
1: Technically, this is possible if you declare object
or dynamic
as the value type, but note that this can lead to a performance hit and poorly maintained code.
Source: https://ru.stackoverflow.com/questions/436634/
All Articles