小编Tre*_*vor的帖子

C# - 迭代并调用类成员

我正在尝试迭代静态类的成员并调用所有字段成员.我在尝试调用该成员的行上遇到MissingFieldException.

像这样的东西:

"找不到字段'NamespaceStuff.MyClass + MyStaticClass.A'."

public class MyClass {
    public MyClass() {
        Type type = typeof(MyStaticClass);
        MemberInfo[] members = type.GetMembers();

        foreach(MemberInfo member in members) {
            if (member.MemberType.ToString() == "Field")
            {
                // Error on this line
                int integer = type.InvokeMember(member.Name,
                                            BindingFlags.DeclaredOnly |
                                            BindingFlags.Public | 
                                            BindingFlags.Instance |
                                            BindingFlags.GetField,
                                            null, null, null);
            }
        }
    }
}

public static class MyStaticClass
{
    public static readonly int A = 1;
    public static readonly int B = 2;
    public static readonly int C = 3;
} …
Run Code Online (Sandbox Code Playgroud)

c# reflection loops class

4
推荐指数
1
解决办法
4834
查看次数

标签 统计

c# ×1

class ×1

loops ×1

reflection ×1