AmbiguousMatchException - Type.GetProperty - C#Reflection

Kus*_*sek 6 c#

昨天我在开发Web部件时遇到了一个问题(这个问题不是关于webpart而是关于C#).关于问题的小背景.我有一个使用Reflection加载WebPart的代码,其中我得到了AmbiguousMatchException.要重现它,请尝试以下代码

        public class TypeA
        {
            public virtual int Height { get; set; }
        }
        public class TypeB : TypeA
        {
            public String Height { get; set; }
        }
        public class Class1 : TypeB
        {

        }

        Assembly oAssemblyCurrent = Assembly.GetExecutingAssembly();
        Type oType2 = oAssemblyCurrent.GetType("AmbigousMatchReflection.Class1");
        PropertyInfo oPropertyInfo2 = oType2.GetProperty("Height");//Throws AmbiguousMatchException 
        oPropertyInfo2 = oType2.GetProperty("Height", 
            BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);  // I tried this code Neither these BindingFlags or any other didnt help
Run Code Online (Sandbox Code Playgroud)

我想知道BindingFlag来获取高度属性.您将有一个问题,我为什么要创建另一个已经存在于Base类中的Height属性.这就是Microsoft.SharePoint.WebPartPages.PageViewerWebPart设计的方法,检查PageViewerWebPart类的Height属性.

Jon*_*eet 13

那里有两个Height属性,它们都没有被你要调用的Class1声明GetProperty.

现在,说你正在寻找"声称尽可能远离类型层次结构的高度属性"是否公平?如果是这样,这里有一些代码可以找到它:

using System;
using System.Diagnostics;
using System.Reflection;

public class TypeA
{
    public virtual int Height { get; set; }
}

public class TypeB : TypeA
{
    public new String Height { get; set; }
}

public class Class1 : TypeB
{        
}

class Test
{
    static void Main()
    {
        Type type = typeof(Class1);
        Console.WriteLine(GetLowestProperty(type, "Height").DeclaringType);
    }

    static PropertyInfo GetLowestProperty(Type type, string name)
    {
        while (type != null)
        {
            var property = type.GetProperty(name, BindingFlags.DeclaredOnly | 
                                                  BindingFlags.Public |
                                                  BindingFlags.Instance);
            if (property != null)
            {
                return property;
            }
            type = type.BaseType;
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您知道返回类型不同,则可能需要简化代码,如sambo99的答案所示.这会使它变得非常脆弱 - 稍后更改返回类型可能会导致只能在执行时发现的错误.哎哟.我说你做完这个的时候无论如何都处于一个脆弱的境地:)