c # - Comment obtenir la variable statique d'une classe [duplicate]

Oct 17 2020

Je développe une application. Il y a tellement de dictionnaires, de listes. En cela, je veux effacer le contenu des dictionnaires statiques, des listes qui commencent par le mot «global». Voici l exemple de code

    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()));
    }

Mais ça ne fonctionne pas. J'obtiens toujours le propertyInfo sous forme de tableau vide. Quelqu'un peut-il me guider là-dessus?

Remarque: j'utilise .net3.5. Visual express 2008. Ceci est fourni par la société, donc je ne peux pas changer la plate-forme.

Réponses

2 YegorAndrosov Oct 17 2020 at 18:37
PropertyInfo[] propertyInfo = myType.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static);

devrait être changé en

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

puisque globalTestNoset globalDictsont des champs (pas des propriétés)