繁体   English   中英

Type.GetProperties不返回任何属性

[英]Type.GetProperties not returning any properties

我试图遍历类中的每个属性,输出属性的名称和值。 但是我的代码没有返回任何属性。

类被循环通过:

public class GameOptions
{
    public ushort Fps;
    public ushort Height;
    public ushort Width;
    public bool FreezeOnFocusLost;
    public bool ShowCursor;
    public bool StaysOnTop;
    public bool EscClose;
    public string Title;
    public bool Debug;
    public int DebugInterval = 500;
}

用于遍历所有代码的代码:

foreach (PropertyInfo property in this.Options.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
    debugItems.Add("Setting Name: " + property.Name);
    debugItems.Add("Setting Value: " + property.GetValue(this,null));
}

但是,当我更改public ushort Fps; public ushort Fps { get; set; } public ushort Fps { get; set; } public ushort Fps { get; set; }它会找到它。

public ushort Fps;
public ushort Height;
...

它们不是属性而是字段。 请尝试使用GetFields 或者,可能更好,将它们转换为属性。 例如

public ushort Fps {get; set;}
public ushort Height {get; set;}

您的类仅包含字段,因此GetProperties返回空数组。

使用GetFields()代替

foreach (FieldInfo field in this.Options.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
    debugItems.Add("Setting Name: " + field.Name);
    debugItems.Add("Setting Value: " + field.GetValue(this));
}

将您的字段更改为属性

public class GameOptions
{
    public ushort Fps { get; set; }
    public ushort Height { get; set; }
    public ushort Width { get; set; }
    // (...)
}

它将之所以会找到public ushort Fps { get; set; } public ushort Fps { get; set; } public ushort Fps { get; set; }但不public ushort Fps; 因为后者是一个字段,而不是一个属性。

对于字段,您将必须使用Type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)

Type.GetFields

GameOptions不包含属性。它们都是字段。

执行此操作时:

public ushort Fps { get; set; }

您正在定义一个auto-implemented属性,这意味着后台将在后台由编译器创建字段。

this.Options.GetType().GetFields();
public class GameOptions
{
    public ushort Fps;
    public ushort Height;
    //...
}

这些是您在那里的字段。


可以使用GetFields方法 ,该方法返回FieldInfo对象的数组:

Type type = this.Options.GetType();
var fields = type.GetFields(
    BindingFlags.Instance |
    BindingFlags.Public |
    BindingFlags.NonPublic);

foreach (var field in fields)
{
    debugItems.Add("Setting Name: " + field.Name);
    debugItems.Add("Setting Value: " + field.GetValue(this));
}

将字段设置为( 自动实现的 )属性:

public class GameOptions
{
    public ushort Fps { get; set; }
    public ushort Height { get; set; }
    //...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM