Jam*_*esW 40 c# reflection static properties class
我试图在一个简单的静态类中循环一些静态属性,以便用它们的值填充组合框,但是遇到了困难.
这是简单的类:
public static MyStaticClass()
{
public static string property1 = "NumberOne";
public static string property2 = "NumberTwo";
public static string property3 = "NumberThree";
}
Run Code Online (Sandbox Code Playgroud)
...以及试图检索值的代码:
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());
}
Run Code Online (Sandbox Code Playgroud)
如果我不提供任何绑定标志,那么我得到大约57个属性,包括System.Reflection.Module模块和我不关心的各种其他继承的东西.我的3个声明的属性不存在.
如果我提供其他标志的各种组合,那么它总是返回0属性.大.
我的静态类是否真的在另一个非静态类中声明是否重要?
我究竟做错了什么?
M4N*_*M4N 54
问题是property1..3不是属性,而是字段.
要使它们属性更改为:
private static string _property1 = "NumberOne";
public static string property1
{
get { return _property1; }
set { _property1 = value; }
}
Run Code Online (Sandbox Code Playgroud)
或者使用自动属性并在类的静态构造函数中初始化它们的值:
public static string property1 { get; set; }
static MyStaticClass()
{
property1 = "NumberOne";
}
Run Code Online (Sandbox Code Playgroud)
...或者myType.GetFields(...)如果字段是您想要使用的话,请使用.
尝试删除BindingFlags.DeclaredOnly,因为根据MSDN:
指定仅应考虑在提供的类型的层次结构级别声明的成员.不考虑继承的成员.
由于静态不能被继承,这可能会导致您的问题.另外我注意到你想要获得的字段不是属性.所以尝试使用
type.GetFields(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37883 次 |
| 最近记录: |