【发布时间】:2017-02-07 16:26:38
【问题描述】:
这是一个由两部分组成的问题。首先,哪些显式属性实现绑定到IAllTogether.SomeInt,为什么编译器不抱怨歧义?当您注释掉标记的行时会这样做。
public interface IFirst
{
int SomeInt { get; }
}
public interface ISecond
{
int SomeInt { get; }
}
public interface ICombined : IFirst, ISecond
{
new int SomeInt { get; } // Comment this line.
}
public interface IAllTogether : IFirst, ISecond, ICombined
{ }
public sealed class Implementation : IAllTogether
{
int ICombined.SomeInt { get { return 0; } } // Comment this line.
int IFirst.SomeInt { get { return 0; } }
int ISecond.SomeInt { get { return 0; } }
}
IAllTogether t = new Implementation();
var unimportant = t.SomeInt;
第二个问题是:当给定接口Type 和属性名称时,如何找到正确的PropertyInfo?我可以使用GetInterfaces() 和GetProperty() 列出所有可能的候选人,但我怎么知道哪个是正确的?我试过typeof(IAllTogether).GetProperty("SomeInt"),但它不起作用。
编辑
看起来第一部分的答案是隐藏继承的成员解决了歧义。然而,关于第二部分甚至没有一条评论:如何可靠地为某些属性名称和接口类型找到正确的PropertyInfo。
编辑 2
澄清问题的第二部分。我正在寻找的是一种为任何未知的Type 获取正确属性的方法。基本上是这样的方法:
public static PropertyInfo GetPropertyOfInterface(Type interfaceType, string propertyName)
{
if (!interfaceType.IsInterface)
throw new ArgumentException();
// for interfaceType == typeof(IAllTogether), return ICombined.SomeInt
// for interfaceType == typeof(IFirst), return IFirst.SomeInt
}
【问题讨论】:
-
如果我运行该代码,我可以看到来自
ICombined的那个被调用,可能是因为new隐藏了另外两个的关键字。顺便说一句:ReSharper 告诉我,在IAllTogether的声明中明确声明IFirst和ISecond是多余的,因为它们无论如何都是通过ICombined继承的。 -
因为
IFirst和ISecond中的SomeInt现在被ICombined中的new SomeInt隐藏,因此将使用ICombined.SomeInt。ICombined.SomeInt的优先级高于其他两个不是因为new关键字。但是因为ICombined实现了另外两个接口。因此它可以隐藏他们的成员。 -
如果我找到第二部分的答案,我会告诉你。
-
您能否为第二个问题指定或举例说明?我在答案中添加了一行。 什么值你想要获得一个属性?正确的属性是
typeof(ICombined).GetProperty("SomeInt")。如果注释行被删除,则取决于您实际调用的内容。 -
@RenéVogt 想象一下,您正在编写一个采用 Type 参数和字符串参数的方法:接口类型和参数名称。该方法需要返回正确的 PropertyInfo 对象。你对 IAllTogether 或 ICombined 一无所知。我将编辑答案以澄清。
标签: c# reflection properties interface language-lawyer