简体   繁体   English

在C#中使用反射

[英]Using reflection in C#

Following this answer, I'm trying to replicate it and iterate over my CustomerModel properties. 按照这个答案,我试图复制它并遍历我的CustomerModel属性。

CustomerModel pippo = new CustomerModel();
Type customer = pippo.GetType();
FieldInfo[] fields = customer.GetFields(BindingFlags.Public | BindingFlags.Instance);

When using the debugger, fields always has a count = 0 but CustomerModel has a lot of public properties I'd like to see in fields. 使用调试器时, fields始终count = 0但是CustomerModel具有很多我想在字段中看到的公共属性。 How can I do that? 我怎样才能做到这一点? Here's an extract of some properties declared I'd like to see. 这是一些我想看的声明的摘录。

    [DataMember]
    public String Id { get; set; }

    [DataMember]
    public String LoginName { get; set; }

    [DataMember]
    public String Password { get; set; }

    [DataMember]
    public String CreationDate { get; set; }

Perhaps the binding flags are incorrect? 也许绑定标志不正确? I'm new to the use of reflection. 我是反射的新手。

Those are properties, not fields. 这些是属性,而不是字段。 Use GetProperties instead of GetFields . 使用GetProperties而不是GetFields

In C#: 在C#中:

public class Foo {

    // this is a field:
    private string _name;

    // this is a property:
    public string Name { get; set; }

    // this is also a property:
    public string SomethingElse { get { return _name; } set { _name = value; } }

}

As Joe correctly pointed out the members in question are properties not fields. 正如乔正确指出的那样,有问题的成员是属性而不是字段。 These are auto-implemented properties and the compiler will generate backing fields for them. 这些是自动实现的属性,编译器将为其生成备用字段。 However these fields won't be public hence the GetFields call fails because it is looking for the public members only. 但是,这些字段不会公开,因此GetFields调用失败,因为它仅在寻找公开成员。 If you want to see the generated fields then change the code to the following 如果要查看生成的字段,则将代码更改为以下内容

FieldInfo[] fields = customer.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

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

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