简体   繁体   中英

Reflection accessing a property if it has a property named “Name”

Using reflection I get a set of PropertyInfo :

var infos = typeof(T).GetProperties(.....)

My object (simplified)

Customer
     Dog   (class with field 'Name')
     Cow   (class with field 'Name')
     FName (string)

When I loop though the infos, I Console Write the Property's value. If the property is a class (Dog, Cow etc) and that class has a "Name" property, then I need to Write the "Name" value.

Basically how do I determine if the MemeberInfo is a class and has a property called "Name" and Write it out?

foreach( var pi in typeof( startingType ).GetProperties() )
{
    var pt = pi.PropertyType;

    if( pt.IsClass && null != pt.GetProperty( "Name" ) )
    {
        Console.WriteLine( pt.Name + " (class with field 'Name')" );
    }
}

@Moho is right, but it doesn't explain how to write the actual name out which I think you want.

This will do it, assuming that your Customer object is in a variable called obj :

        foreach (var pi in typeof(T).GetProperties())
        {
            var propertyValue = pi.GetValue(obj); // This is the Dog or Cow object
            var pt = pi.PropertyType;

            var nameProperty = pt.GetProperty("Name");
            if (pt.IsClass && nameProperty != null)
            {
                var name = nameProperty.GetValue(propertyValue); // This pulls the name off of the Dog or Cow
                Console.WriteLine(name);
            }
        }

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