gpt4 book ai didi

c# - 是否可以创建具有两个同名属性的类型?

转载 作者:行者123 更新时间:2023-12-05 08:37:47 26 4
gpt4 key购买 nike

根据documentation , Type.GetProperty(string, BindingFlags) 抛出 AmbiguousMatchException when:

More than one property is found with the specified name and matchingthe specified binding constraints

我正在寻找一种示例类型,其中 GetProperty 方法会抛出异常,因为找到多个具有相同名称的属性。我创建了一个继承关系 (A : B),其中两个类都定义了相同的命名公共(public)属性(使用 new 关键字),其中 BindingFlags = Public |实例,但不会抛出。

最佳答案

在C#中,一个类可以实现多个索引器,所有索引器都称为Item

public class Class1
{
public string this[int firstParameter]
{
get { return ""; }
}

public string this[string firstParameter, int secondParameter]
{
get { return ""; }
}
}

然后你可以使用这个产生异常:

class Program
{
static void Main()
{
// This will throw AmbiguousMatchException:
typeof(Class1).GetProperty("Item", BindingFlags.Public | BindingFlags.Instance);
}
}

这将产生具有单个类和 PublicInstance 绑定(bind)标志的 AmbiguousMatchException

关于c# - 是否可以创建具有两个同名属性的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64487350/

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