如何在C#类中使用它的JSONPROPERTY属性访问变量的值?

发布于 2025-02-11 23:35:27 字数 800 浏览 2 评论 0原文

我有此类:

public class Configuration
{
   [JsonProperty("B_C.Parameter.fixtureHeight")]
   public string BCParameterfixtureHeight { get; set; }
}

我想使用bcparameterfuixture Height使用其b_c.parameter.fixtureheight的JSONProperty名称。

我已经尝试过,我认为应该有效:

Configuration config = new Configuration();
config.BCParameterfixtureHeight = "1";

var a = [config].GetType().GetProperties().FirstOrDefault(p => 
p.GetCustomAttributes<JsonPropertyAttribute>().Any(at => 
at.PropertyName.Equals("B_C.Parameter.fixtureHeight")));

但是,我得到了一个“编译器错误CS1525”和[config]中的开头支架下的红线。编译器说

“无效的表达式'['。“

I have this class:

public class Configuration
{
   [JsonProperty("B_C.Parameter.fixtureHeight")]
   public string BCParameterfixtureHeight { get; set; }
}

I want to access the value of BCParameterfixtureHeight using its JsonProperty name of B_C.Parameter.fixtureHeight.

I've tried this which I think should work:

Configuration config = new Configuration();
config.BCParameterfixtureHeight = "1";

var a = [config].GetType().GetProperties().FirstOrDefault(p => 
p.GetCustomAttributes<JsonPropertyAttribute>().Any(at => 
at.PropertyName.Equals("B_C.Parameter.fixtureHeight")));

However, I'm getting a "Compiler Error CS1525" and a red line under the opening bracket in [config]. The compiler is saying

"Invalid expression term '['."

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

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

发布评论

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

评论(1

独守阴晴ぅ圆缺 2025-02-18 23:35:27

您在config上放置的括号是问题所在。

您应该写:

var a = config.GetType() //...

编辑:

正如克里斯·施勒(Chris Schaller)在评论中提到的那样,您可以通过将预计的参数提供给getCustomatTributes来修复初始错误。

     var a = config.GetType().GetProperties().FirstOrDefault(p => 
        p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Any(at => at is JsonPropertyAttribute && (at as JsonPropertyAttribute).PropertyName.Equals("B_C.Parameter.fixtureHeight"))
     );

The brackets you put around config are the problem.

You should write:

var a = config.GetType() //...

EDIT:

As Chris Schaller mentionned in the comments, you can fix your initial errors by giving the expeted arguments to GetCustomAttributes.

     var a = config.GetType().GetProperties().FirstOrDefault(p => 
        p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Any(at => at is JsonPropertyAttribute && (at as JsonPropertyAttribute).PropertyName.Equals("B_C.Parameter.fixtureHeight"))
     );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文