C# 为什么允许从MemberInfo强制转换为MethodInfo?
用于System.Reflection的文档。具有以下示例:C# 为什么允许从MemberInfo强制转换为MethodInfo?,c#,.net,reflection,system.reflection,C#,.net,Reflection,System.reflection,用于System.Reflection的文档。具有以下示例: foreach (MemberInfo mi in t.GetMembers()) { if (mi.MemberType == MemberTypes.Method) { foreach (ParameterInfo pi in ((MethodInfo)mi).GetParameters()) 请注意cast(MethodInfo)mi)MemberInfo和MethodInfo没有共同的父项
foreach (MemberInfo mi in t.GetMembers())
{
if (mi.MemberType == MemberTypes.Method)
{
foreach (ParameterInfo pi in ((MethodInfo)mi).GetParameters())
请注意cast
(MethodInfo)mi)
MemberInfo
和MethodInfo
没有共同的父项,那么为什么允许强制转换?MethodInfo
继承自MemberInfo
的MethodBase
[SerializableAttribute]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
public abstract class MethodInfo : MethodBase,
_MethodInfo
是派生自,它是派生自。请注意,封闭的
if
中的mi.MemberType==MemberTypes.Method
条件在运行时防止出现InvalidCastException
正如答案已经解释的那样,MethodInfo
间接源自MemberInfo
。此外,在运行时,这不会引发错误,因为您正在筛选属于方法的成员,因此在运行该代码时保证为MethodInfo
。好的,我明白您的意思。MemberInfo->MethodBase->MethodInfo。但是,还要注意,强制转换是从父对象到子对象的,这也是错误的。我不认为多态性与这种情况有什么关系。如果我有类b:a
,并且我尝试执行(b)newa()
,它将抛出异常(MethodInfo)mi)
本质上是一样的。不允许从父级向上转换为子级。@newprint是-简单的示例,假设有三种类型A
,B
,和C
<代码>B和C
继承自A
。如果它实际上是目标类型,则可以将A
强制转换为它的一个子项。例如A A=newb();B=(B)a代码>是有效的。在您的评论中,(b)new a()
实际上是无效的,因为a
的实例不是b
@newprint多态性允许您将MethodInfo
的实例分配给声明为MemberInfo
的变量,然后将其转换回MethodInfo
。这正是你引用的代码中发生的事情。@jdpenix哦,看看我哪里错了mi
实际上指向MethodInfo
的类型。
[SerializableAttribute]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
public abstract class MethodBase : MemberInfo,
_MethodBase