Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么允许从MemberInfo强制转换为MethodInfo?_C#_.net_Reflection_System.reflection - Fatal编程技术网

C# 为什么允许从MemberInfo强制转换为MethodInfo?

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没有共同的父项

用于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
没有共同的父项,那么为什么允许强制转换?

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