【问题标题】:c# - How to get the static variable of a class [duplicate]c# - 如何获取类的静态变量[重复]
【发布时间】:2020-10-17 11:18:34
【问题描述】:

我正在开发一个应用程序。有这么多的字典,列表。在此,我想清除以“全局”一词开头的静态字典、列表的内容。这是示例代码

    public static Dictionary<string, TestNo> globalDict = new Dictionary<string, TestNo>();
    public static List<TestNo> globalTestNos= new List<TestNo>(); 
    public Form1()
    {
        InitializeComponent();
        globalDict.Add("a", 1);
        globalDict.Add("b", 2);
        globalDict.Add("c", 3);
    }
    private void button1_Click(object sender, EventArgs e)
    {
        // Get the type of 'MyClass'.
        Type myType = this.GetType();

        PropertyInfo[] propertyInfo = myType.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public |
            BindingFlags.Static);
        List<string> temp = propertyInfo.Where(x => x.Name.Contains("global")).Select(x => x.Name).ToList();
        MessageBox.Show(String.Join(Environment.NewLine,temp.ToArray()));
    }

但它不起作用。我总是将 propertyInfo 作为空数组。有人可以指导我吗?

注意:我使用的是 .net3.5。 Visual express 2008。这是公司提供的,所以不能换平台。

【问题讨论】:

  • 分享TestNo 班级和myclass 以清除您的问题
  • @SaeedEsmaeelinejad TestNo 不需要回答这个问题。 myclass 已显示。
  • globalDict 和 globalTestNos 是字段,因此您应该使用 GetFields 或将它们设为属性。

标签: c# .net linq


【解决方案1】:
PropertyInfo[] propertyInfo = myType.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static);

应该改为

FieldInfo[] fieldInfos = myType.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static);

因为globalTestNos 和globalDict 是字段(不是属性)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2012-02-04
    • 2015-06-12
    • 1970-01-01
    • 2014-01-03
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多