繁体   English   中英

C#反映类字段

[英]C# Reflection of a class field

我搜索了但没有找到正确的答案。

假设我们有一个类似的类:

public sealed Class Foo{
     public static readonly Foo x;
     public static readonly Foo y;
     public static readonly Foo z;
     public static readonly Foo t;

     public string Name{get;}
     public int Value{get;}
     public Foo(string name,int val){//properties sets here}
} 

我有一个像这样的enum

public enum FooFinder{
  x,
  y,
  z,
  t
}

我在另一个FooLib.dllFooFinder库中创建了这个Foo类。

我想使用我的枚举类返回Foo.x,Foo.y类型。

 private static Foo GetFoo (FooFinder Level)
    {
        FieldInfo[] props = typeof(Foo).GetFields();

        foreach (FieldInfo item in props)
        {

            if (item.Name == Enum.GetName(typeof(FooFinder), Level))
            {
                 // I could create an instance of Foo with Activator.CreateInstance() 
                 // but I want to return Foo class' chosen field by FooFinder enum
            }
        }

    }

我希望我能解释我想做什么。 那么如何通过反思来获得Foo班的所选字段呢? 或我可以得到吗?

也许您可以使用:

private static Foo GetFoo (FooFinder Level)
{
    var fieldInfo = typeof(Foo).GetField(Enum.GetName(typeof(FooFinder), level), BindingFlags.Static | BindingFlags.Public);
    return fieldInfo?.GetValue(null) as Foo;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM