[英]Dynamic object properties in C# and Javascript
I have a table in the database for various settings in my application. 我在数据库中有一个表,用于我的应用程序中的各种设置。 These settings can be added to or changed at any time. 可以随时添加或更改这些设置。 I would like to pull them out of the db into an object and reference them in both my server code (C#) and client code (JS). 我想将它们从数据库中拉出到一个对象中,并在我的服务器代码(C#)和客户端代码(JS)中引用它们。
SettingGroup SettingName type value
Core defaultPagingSize numeric 5
Core pagingType text dynamic
Ecommerce showGallery boolean true
In javascript I can just put them into a JSON object and reference them like this: 在javascript中我可以将它们放入JSON对象并像这样引用它们:
var size = settings.core.defaultPagingSize;
Is there a similar way I can do this in C#? 有没有类似的方法我可以在C#中做到这一点?
int size = settings.core.defaultPagingSize;
No. 没有。
The new dynamic
keyword that will be added for .NET and C# 4.0 will handle what you're seeking, but in the current .NET and C# versions, there's no support for this. 将为.NET和C#4.0添加的新dynamic
关键字将处理您正在寻找的内容,但在当前的.NET和C#版本中,不支持这一点。
You should be able to get this to work though: 你应该能够让它工作:
int size = settings["core"]["defaultPagingSize"].ToInt32();
or something similar. 或类似的东西。
In .NET, the most immediate answer would be to use a dictionary (perhaps nested) of some kind. 在.NET中,最直接的答案是使用某种字典(可能是嵌套的)。 C# 4.0 introduces some dynamic concepts, but you'd need to write a fair bit of code to get it to behave like javascript. C#4.0引入了一些动态概念,但是你需要编写一些代码才能让它像javascript一样运行。
Alternatively, store them as typed records in a flat list and use LINQ: 或者,将它们存储为平面列表中的类型记录并使用LINQ:
var setting = settings.Single(x=>x.Group == "Core"
&& x.Name == "defaultPagingSize");
int value = int.Parse(setting.Value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.