C# - 从静态类的静态获取属性的值 [英] C# - Get values of static properties from static class

查看:1452
本文介绍了C# - 从静态类的静态获取属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过一个简单的静态类中的一些静态属性试图循环,以填充与他们的价值观的组合框,但我有困难。

I'm trying to loop through some static properties in a simple static class in order to populate a combo box with their values, but am having difficulties.

下面是一个简单的类:

public static MyStaticClass()
{
    public static string property1 = "NumberOne";
    public static string property2 = "NumberTwo";
    public static string property3 = "NumberThree";
}

...和code试图检索值:

... and the code attempting to retrieve the values:

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声明的属性不是present。

If I don't supply any binding flags then I get about 57 properties including things like System.Reflection.Module Module and all sorts of other inherited things I don't care about. My 3 declared properties are not present.

如果我公司供应其他标志的各种组合,那么它总是返回0的属性。太好了。

If I supply various combinations of other flags then it always returns 0 properties. Great.

不要紧,我的静态类是另一个非静态类中实际声明?

Does it matter that my static class is actually declared within another non-static class?

我在做什么错了?

推荐答案

的问题是, property1..3 不是性能,而是各个领域。

The problem is that property1..3 are not properties, but fields.

为了让他们的属性将其更改为:

To make them properties change them to:

private static string _property1 = "NumberOne";
public static string property1
{
  get { return _property1; }
  set { _property1 = value; }
}

也可以使用自动属性和在类的静态构造函数初始化它们的值:

Or use auto properties and initialize their values in the static constructor of the class:

public static string property1 { get; set; }

static MyStaticClass()
{
  property1 = "NumberOne";
}

...或使用 myType.GetFields(...)如果字段要使用的东西。

...or use myType.GetFields(...) if fields are what you want to use.

这篇关于C# - 从静态类的静态获取属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆