使用 BindingFlags.Public 的 GetProperties 方法没有返回任何内容。

41

可能是一个愚蠢的问题,但我在网上找不到任何解释。
这段代码为什么不能工作? 这段代码应该将Contact(源)的属性值复制到新实例化的ContactBO(目标)对象中。

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;
        }
    }
}
两个类具有相同的属性名称(BO类有一些其他属性,但在初始化时不重要)。两个类仅具有公共属性。 当我运行上面的示例时,destinationPropssourceProps长度为零。

但是,当我使用BindingFlags.Instance扩展GetProperties方法时,它突然返回所有内容。希望有人能够对此事情进行解释,因为我很迷茫。


1
如果您想将 propertyToSetnull 进行比较,则不应使用 First,因为如果找不到不匹配谓词的项,它会抛出异常。请改用 FirstOrDefault - ba__friend
2
为了帮助那些和我一样关注属性和字段差异的人,试试 GetFields() 方法。 - CAD bloke
2个回答

63

根据GetProperties方法的文档:

为了获得返回值,您必须指定BindingFlags.Instance或BindingFlags.Static。


2
这正是我正在做的事情。提出问题的原因是为什么BindingFlags.Public没有返回公共属性?嗯,我想这就是框架的工作方式。 - Nikola Kolev

34

这种行为是因为你必须在BindingFlags中指定Static或Instance成员。BindingFlags是一个标志枚举,可以使用|(按位或)组合。

你需要的是:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接