【问题标题】:C# - Get values of static properties from static classC# - 从静态类中获取静态属性的值
【发布时间】:2010-12-02 01:15:30
【问题描述】:

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

这是一个简单的类:

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

我的静态类实际上是在另一个非静态类中声明的吗?

我做错了什么?

【问题讨论】:

  • @Veverke:考虑到 OP 犯了其他人也可能犯的错误,因此保留不正确的术语对于确保 Google 能够找到该帖子至关重要。这样的编辑会破坏问题,因为在您进行编辑后没有留下任何问题。

标签: c# reflection class static properties


【解决方案1】:

问题在于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(值);好像没问题?
【解决方案2】:

尝试删除BindingFlags.DeclaredOnly,因为根据 MSDN:

指定只有成员声明 在提供类型的级别 应考虑层次结构。 不考虑继承的成员。

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

type.GetFields(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多