简体   繁体   English

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

[英]How can I access the value of a variable using it's JsonProperty attribute in a C# class?

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 .我想使用 B_C.Parameter.fixtureHeight 的B_C.Parameter.fixtureHeight名称访问BCParameterfixtureHeight的值。

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].但是,我在 [config] 中的左括号下方收到"Compiler Error CS1525"和一条红线。 The compiler is saying编译器在说

"Invalid expression term '['." “无效的表达式术语'['。”

The brackets you put around config are the problem.您放在config周围的括号是问题所在。

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 .正如 Chris Schaller 在评论中提到的那样,您可以通过将 expeted 参数提供给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"))
     );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在c#中访问属性属性中的类变量? - How can I access to class variable in property attribute in c#? 我可以在C#中的JsonProperty属性中使用资源字符串吗? - Can I use Resource Strings in a JsonProperty Attribute in C#? 在 C# 中,如何在运行时设置、重置或定义 JsonProperty 属性? - In C#, how can I set, reset, or define a JsonProperty attribute at runtime? 我如何检查数据库的属性值C# - how can i check database's attribute value C# 如何使用JSON文件中生成的JsonProperty Name = name来访问相应C#类中的单个元素 - How do I use the generated JsonProperty Name = name from JSON file to access a single element in a corresponding C# Class 使用 JsonProperty 属性中的指定路径将 C# 类序列化为嵌套的 JSON - Serialize C# class into nested JSON with specified paths in JsonProperty attribute 属性 [JsonProperty] 用于重命名 C# 中 DTO class 的属性 - Attribute [JsonProperty] for rename property of DTO class in C# 使用C#,如何使用参数访问VB类的默认属性的getter / setter? - Using C#, how can I access the getter/setter of a VB class's default property with parameter? C#:如何从基类属性中导出new属性的值? - C#: how can I derive the value of new attribute from the base class attribute? 在C#中使用类的Attribute参数的值作为Property的属性值 - Using a class's Attribute parameter's value in as a Property's attribute value in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM