C# Equilavent of "dynamic" JavaScript 对象?



我想创建一个具有字符串键的单个对象(可能是Dictionary(,这些字符串键将具有不同的变量类型作为值(string、int、bool、Dictionary<string、string>等(。这可能吗?

*我知道这可能只是两种语言的根本区别——方钉圆孔

您可以使用dynamic作为值类型,它比object更好地匹配问题,并且您不需要将来的铸件:

var dictionary = new Dictionary<string, dynamic>();
dictionary.Add("1", 10);
dictionary.Add("2", "test");
dictionary.Add("3", true);
foreach ( var item in dictionary )
Console.WriteLine($"{item.Key} is type: {item.Value.GetType().Name} = {item.Value}");
Console.WriteLine();
int v = dictionary["1"] + 10;
Console.WriteLine(v);
string s = dictionary["2"] + " one";
Console.WriteLine(s);
bool b = !dictionary["3"];
Console.WriteLine(b);

输出

1 is type: Int32 = 10
2 is type: String = test
3 is type: Boolean = True
20
test one
False

https://learn.microsoft.com/dotnet/csharp/programming-guide/types/using-type-dynamic

Dictionary<string, object>大致相当于JavaScript中的对象。

示例:

var dictionary = new Dictionary<string, object>
{
"myString" = "helloWorld",
"myChild" = new Dictionary<string, object>
{
"myName" = "bobby tables"
}
};
var myString = (string)dictionary["myString"];
var myName = (string)((Dictionary<string, object>)dictionary["myChild"])["myName"];

您也可以使用dynamic关键字和ExpandoObject

dynamic obj = new ExpandoObject();
obj.MyString = "helloWorld";
obj.MyChild = new ExpandoObject();
obj.MyChild.MyName = "bobby tables";
string myString = obj.MyString;
string myName = obj.MyChild.MyName;

最新更新