简体   繁体   中英

Method GetProperties with BindingFlags.Public doesn't return anything

Probably a silly question, but I couldn't find any explanation on the web.
What is the specific reason for this code not working? The code is supposed to copy the property values from the Contact (source) to the newly instantiated ContactBO (destination) object.

public ContactBO(Contact contact)
{
    Object source = contact;
    Object destination = this;

    PropertyInfo[] destinationProps = destination.GetType().GetProperties(
        BindingFlags.Public);
    PropertyInfo[] sourceProps = source.GetType().GetProperties(
        BindingFlags.Public);

    foreach (PropertyInfo currentProperty in sourceProps)
    {
        var propertyToSet = destinationProps.First(
            p => p.Name == currentProperty.Name);

        if (propertyToSet == null)
            continue;

        try
        {
            propertyToSet.SetValue(
                destination, 
                currentProperty.GetValue(source, null), 
                null);
        }
        catch (Exception ex)
        {
            continue;
        }
    }
}

Both classes have the same property names (the BO class has a few other but they don't matter on initialization). Both classes have only public properties. When I run the example above, destinationProps and sourceProps have lengths of zero.

But when I expand the GetProperties method with BindingFlags.Instance , it suddenly returns everything. I would appreciate if someone could shed light on that matter because I'm lost.

From the documentation of the GetProperties method:

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

This behaviour is because you must specify either Static or Instance members in the BindingFlags. BindingFlags is a flags enum that can be combined using | (bitwise or).

What you want is:

.GetProperties(BindingFlags.Instance | BindingFlags.Public);

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