C# 和 Javascript 中的动态对象属性

发布于 2024-07-13 23:13:44 字数 538 浏览 6 评论 0原文

我在数据库中有一个表用于我的应用程序中的各种设置。 可以随时添加或更改这些设置。 我想将它们从数据库中提取到一个对象中,并在我的服务器代码(C#)和客户端代码(JS)中引用它们。

SettingGroup SettingName        type      value
Core         defaultPagingSize  numeric   5
Core         pagingType         text      dynamic
Ecommerce    showGallery        boolean   true

在 javascript 中,我可以将它们放入 JSON 对象中并像这样引用它们:

var size = settings.core.defaultPagingSize;

是否有类似的方法可以在 C# 中执行此操作?

int size = settings.core.defaultPagingSize;

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).

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:

var size = settings.core.defaultPagingSize;

Is there a similar way I can do this in C#?

int size = settings.core.defaultPagingSize;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一刻暧昧 2024-07-20 23:13:44

不会。

将为 .NET 和 C# 4.0 添加的新 dynamic 关键字将处理您正在寻找的内容,但在当前的 .NET 和 C# 版本中,不支持此操作。

你应该能够让它工作:

int size = settings["core"]["defaultPagingSize"].ToInt32();

或者类似的东西。

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.

You should be able to get this to work though:

int size = settings["core"]["defaultPagingSize"].ToInt32();

or something similar.

岁吢 2024-07-20 23:13:44

在 .NET 中,最直接的答案是使用某种字典(可能是嵌套的)。 C# 4.0 引入了一些动态概念,但您需要编写大量代码才能使其表现得像 JavaScript。

或者,将它们作为类型记录存储在平面列表中并使用 LINQ:

var setting = settings.Single(x=>x.Group == "Core"
         && x.Name == "defaultPagingSize");
int value = int.Parse(setting.Value);

In .NET, the most immediate answer would be to use a dictionary (perhaps nested) of some kind. 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.

Alternatively, store them as typed records in a flat list and use LINQ:

var setting = settings.Single(x=>x.Group == "Core"
         && x.Name == "defaultPagingSize");
int value = int.Parse(setting.Value);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文