deo*_*oll 7 .net c# reflection constants
我有一个类如下:
public class MyConstants
{
public const int ONE = 1;
public const int TWO = 2;
Type thisObject;
public MyConstants()
{
thisObject = this.GetType();
}
public void EnumerateConstants()
{
PropertyInfo[] thisObjectProperties = thisObject.GetProperties(BindingFlags.Public);
foreach (PropertyInfo info in thisObjectProperties)
{
//need code to find out of the property is a constant
}
}
}
Run Code Online (Sandbox Code Playgroud)
基本上它正试图反思自己.我知道如何反映字段ONE和TWO.但我怎么知道它是不是常数?
Wal*_*t W 16
那是因为他们是田地,而不是财产.尝试:
public void EnumerateConstants() {
FieldInfo[] thisObjectProperties = thisObject.GetFields();
foreach (FieldInfo info in thisObjectProperties) {
if (info.IsLiteral) {
//Constant
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:DataDink是正确的,使用IsLiteral更顺畅
FieldInfo对象实际上有很多"IsSomething"布尔值:
var m = new object();
foreach (var f in m.GetType().GetFields())
if (f.IsLiteral)
{
// stuff
}
Run Code Online (Sandbox Code Playgroud)
无论如何,这样可以节省一小部分代码,而无需检查属性.
归档时间: |
|
查看次数: |
11402 次 |
最近记录: |