C#-从静态类获取静态属性的值

C#-从静态类获取静态属性的值,c#,reflection,class,static,properties,C#,Reflection,Class,Static,Properties,我试图在一个简单的静态类中循环一些静态属性,以便用它们的值填充组合框,但遇到了一些困难 下面是一个简单的类: public static MyStaticClass() { public static string property1 = "NumberOne"; public static string property2 = "NumberTwo"; public static string property3 = "NumberThree"; } 。。。以及尝试检

我试图在一个简单的静态类中循环一些静态属性,以便用它们的值填充组合框,但遇到了一些困难

下面是一个简单的类:

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个属性。太好了

我的静态类实际上是在另一个非静态类中声明的,这有关系吗


我做错了什么?

问题是
属性1..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。仅声明
,因为根据MSDN:

指定仅声明成员 在所提供类型的级别 应考虑等级制度。 不考虑继承的成员

由于无法继承静态的,这可能会导致您的问题。我还注意到您试图获取的字段不是属性。所以试着使用

type.GetFields(...)

我使用的是:var type=newfoo().GetType();var value=type.GetField(“Field1”).GetValue(new Foo());控制台写入线(值);这看起来还好吗?@Veverke:考虑到OP犯了其他人也可能犯的错误,所以保留不正确的术语对于确保Google能够找到帖子至关重要。这样的编辑会破坏问题,因为在您进行编辑后没有问题了。