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

43

我正在尝试循环访问一个简单静态类中的一些静态属性,以便将它们的值填充到组合框中,但是遇到了困难。

这是简单的类:

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 Module和所有其他继承的东西,这些都不重要。 我声明的3个属性不存在。

如果我提供其他标志的各种组合,它总是返回0个属性。 太好了。

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

我做错了什么?


1
@Veverke:考虑到原帖作者犯了这个错误,其他人也可能会犯同样的错误,因此保留不正确的术语对于确保谷歌能够找到该帖子至关重要。这样的编辑会破坏问题本身,因为在进行编辑后就没有问题可言了。 - David Mulder
2个回答

57
问题在于property1..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(...)


我正在使用类似以下代码: var type = new Foo().GetType(); var value = type.GetField("Field1").GetValue(new Foo()); Console.WriteLine(value); 看起来可以吗? - Dan Csharpster

6
尝试删除 BindingFlags.DeclaredOnly,因为根据 MSDN 上的说明:

指定仅考虑在提供的类型层次结构级别声明的成员。未继承的成员将不会被考虑。

由于静态成员无法被继承,这可能导致您的问题。另外我注意到你尝试获取的字段不是属性,所以请尝试使用
type.GetFields(...)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接