简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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