簡體   English   中英

如何使用 C# 類中的 JsonProperty 屬性訪問變量的值?

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

我有這堂課:

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

我想使用 B_C.Parameter.fixtureHeight 的B_C.Parameter.fixtureHeight名稱訪問BCParameterfixtureHeight的值。

我已經嘗試過這個我認為應該可行的方法:

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")));

但是,我在 [config] 中的左括號下方收到"Compiler Error CS1525"和一條紅線。 編譯器在說

“無效的表達式術語'['。”

您放在config周圍的括號是問題所在。

你應該寫:

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

編輯:

正如 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM