c# - 使用反射获取类属性信息不返回任何内容

标签 c# reflection

我的任务是更新大量具有相同数据类型的记录,并且希望以这样的方式编写它,我不必找到每个类对象并手动执行它们。因此,我认为最好的方法是使用 PropertyInfo 进行反射。

在提出这个问题之前,我已经查看了以下内容;

Getting ALL the properties of an object How to get the list of properties of a class? https://www.codegrepper.com/code-examples/csharp/c%23+get+all+class+properties https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=net-5.0

看看这个,表明我的方法是正确的,但我一生都没有得到结果。

代码如下

void Main()
{
    var propeties =  typeof(MaterialsStructure).GetProperties(BindingFlags.Public | BindingFlags.Static);

}

public class MaterialsStructure
{
    public ExistingProposedDescriptionStructure boundariesField;

    public ExistingProposedDescriptionStructure ceilingsField;
}

public class ExistingProposedDescriptionStructure
{

    public string Existing { get; set; }
    public string Proposed { get; set; }
    public bool NotApplicable { get; set; }
    public bool DontKnow { get; set; } 
}

问题是,当我检查属性时,它在数组中有 0 个项目,而我原本期望它有两个 ExistingProposedDescriptionStructure 类型的属性。如果有人能告诉我我哪里出了问题,我将不胜感激。

最佳答案

您的MaterialsStructure类没有属性,它有字段。请参阅here了解更多详情。所以要么这样做:

var fields = typeof(MaterialsStructure).GetFields();

或者改变你的类(class):

public class MaterialsStructure
{
    public ExistingProposedDescriptionStructure boundariesField { get; set;}
    public ExistingProposedDescriptionStructure ceilingsField { get; set;}
}

现在这可以工作了:

var propeties = typeof(MaterialsStructure).GetProperties();

关于c# - 使用反射获取类属性信息不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66064505/

相关文章:

c# - VS 2012 sqlite 设计时间

c# - 枚举表达式列表以过滤集合

c# - 有什么方法可以在 C# 中创建引用 List<T> 元素的 Span<T> 或 Memory<T> 吗?

c# - 客户端 C# 在 asp.net 中给出错误

java - 如何使用反射(Java)调用私有(private)静态方法?

java 字段变化监听器

C# 将 {CRLF} 替换为 {LF}

Java 反射 - 获取包列表

javascript - 获取传递给函数的 Javascript 'type'

c# - 使用带反射的 XPath 样式查询