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

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

我是反射的新手,我想知道如何过滤掉私有属性并且只获取实例化的属性。下面给出了我想要实现的示例。

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";

当我获取对象 pd 的属性时,我想过滤掉私有且未实例化的属性,例如属性 TempValue , IdAddressDetails

提前致谢。

也许这个

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();

其他资源

BindingFlags Enum

Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.

PropertyInfo.GetValue Method

Returns the property value of a specified object.