方法GetProperties with BindingFlags.Public不返回任何内容

Nik*_*lev 33 c# reflection

可能是一个愚蠢的问题,但我在网上找不到任何解释.
这段代码不起作用的具体原因是什么?该代码应该将属性值从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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

两个类都具有相同的属性名称(BO类有一些其他类,但它们在初始化时无关紧要).这两个类都只有公共属性.当我运行上面的例子,destinationProps 并且 sourceProps长度为零.

但是当我扩展GetProperties方法时BindingFlags.Instance,它会突然返回所有内容.我很感激,如果有人可以解释这件事,因为我迷路了.

Joã*_*elo 49

GetProperties方法的文档:

您必须指定BindingFlags.Instance或BindingFlags.Static才能获得返回.

  • 这正是我正在做的。问题的原因是为什么 BindingFlags.Public 不返回公共属性?好吧,我想这就是框架的工作方式。 (2认同)

dri*_*iis 28

此行为是因为您必须在BindingFlags中指定静态成员或实例成员.BindingFlags是一个标志枚举,可以使用|(按位或)组合.

你想要的是:

.GetProperties(BindingFlags.Instance | BindingFlags.Public);
Run Code Online (Sandbox Code Playgroud)