簡體   English   中英

C# - 從靜態類中獲取靜態屬性的值

[英]C# - Get values of static properties from static class

我試圖在一個簡單的靜態類中循環一些靜態屬性,以便用它們的值填充組合框,但是遇到了困難。

這是簡單的類:

public static MyStaticClass()
{
    public static string property1 = "NumberOne";
    public static string property2 = "NumberTwo";
    public static string property3 = "NumberThree";
}

...以及試圖檢索值的代碼:

Type myType = typeof(MyStaticClass);
PropertyInfo[] properties = myType.GetProperties(
       BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (PropertyInfo property in properties)
{
    MyComboBox.Items.Add(property.GetValue(myType, null).ToString());
}

如果我不提供任何綁定標志,那么我得到大約57個屬性,包括System.Reflection.Module模塊和我不關心的各種其他繼承的東西。 我的3個聲明的屬性不存在。

如果我提供其他標志的各種組合,那么它總是返回0屬性。 大。

我的靜態類是否真的在另一個非靜態類中聲明是否重要?

我究竟做錯了什么?

問題是property1..3不是屬性,而是字段。

要使它們屬性更改為:

private static string _property1 = "NumberOne";
public static string property1
{
  get { return _property1; }
  set { _property1 = value; }
}

或者使用自動屬性並在類的靜態構造函數中初始化它們的值:

public static string property1 { get; set; }

static MyStaticClass()
{
  property1 = "NumberOne";
}

...或者如果您想要使用字段,請使用myType.GetFields(...)

嘗試刪除BindingFlags.DeclaredOnly ,因為根據MSDN:

指定僅應考慮在提供的類型的層次結構級別聲明的成員。 不考慮繼承的成員。

由於靜態不能被繼承,這可能會導致您的問題。 另外我注意到你想要獲得的字段不是屬性。 所以嘗試使用

type.GetFields(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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