简体   繁体   English

如何使用C#反射获取实例化的属性或不为null的类类型的属性

[英]How to use C# reflection to get properties that are instantiated or properties of a class type that are not null

I'm new to reflection, I want to know how to filter out the private properties and also get only the properties that are instantiated. 我是反射的新手,我想知道如何过滤私有属性,并且还仅获取实例化的属性。 Sample of what I would like to achieve is given below. 我想要实现的示例如下。

public class PersonalDetails
{
    internal Address AddressDetails { get; set; }
    public Contact ContactDetals { get; set; }
    public List<PersonalDetails> Friends { get; set; }
    public string FirstName { get; set; }
    private int TempValue { get; set; }
    private int Id { get; set; }

    public PersonalDetails()
    {
        Id = 1;
        TempValue = 5;
    }
}

public class Address
{
    public string MailingAddress { get; set; }
    public string ResidentialAddress { get; set; }
}

public class Contact
{
    public string CellNumber { get; set; }
    public string OfficePhoneNumber { get; set; }
}

PersonalDetails pd = new PersonalDetails();
pd.FirstName = "First Name";
pd.ContactDetals = new Contact();
pd.ContactDetals.CellNumber = "666 666 666";

When I get the properties of object pd I want to filter out the properties that are private and not instantiated, like properties TempValue , Id and AddressDetails 当我获得对象pd的属性时,我想过滤掉私有的且未实例化的属性,例如TempValueIdAddressDetails属性

Thanks in advance. 提前致谢。

Maybe this 也许这个

var p = new PersonalDetails();

var properties = p.GetType()
                  .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                  .Where(x => x.GetValue(p) != null && !x.GetMethod.IsPrivate && !x.SetMethod.IsPrivate)
                  .ToList();

Additional Resources 其他资源

BindingFlags Enum BindingFlags枚举

Specifies flags that control binding and the way in which the search for members and types is conducted by reflection. 指定用于控制绑定的标志以及通过反射进行成员和类型搜索的方式。

PropertyInfo.GetValue Method PropertyInfo.GetValue方法

Returns the property value of a specified object. 返回指定对象的属性值。

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

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