[英]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.