gpt4 book ai didi

c# - AmbiguousMatchException - Type.GetProperty - C# 反射

转载 作者:太空狗 更新时间:2023-10-29 20:52:31 25 4
gpt4 key购买 nike

昨天我在开发 Web 部件时遇到了一个问题(这个问题不是关于 webpart 而是关于 C#)。关于这个问题的背景很少。我有一个使用反射加载 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

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

最佳答案

那里有两个 Height 属性,它们都不是由您调用 GetProperty 的 Class1 声明的。

现在,可以说您正在寻找“在类型层次结构中声明的 Height 属性尽可能低”吗?如果是这样,这里有一些代码可以找到它:

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;
}
}

请注意,如果您知道返回类型会有所不同,可能可以简化代码,如sambo99's answer 所示。 .不过,这会使它变得非常脆弱——稍后更改返回类型可能会导致只能在执行时发现的错误。哎哟。我想说的是,当您完成此操作时,无论如何您都处于脆弱的境地:)

关于c# - AmbiguousMatchException - Type.GetProperty - C# 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/994698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com