c# - RuntimeMethodInfo 相等 : bug?

标签 c# .net reflection

让我们开始:

using System;

public class Program
{
    class A
    {
        public virtual void Do() { }
    }

    class B:A
    {
    }

    public static void Main()
    {
        var m1 = typeof(A).GetMethod("Do");
        var m2 = typeof(B).GetMethod("Do");

        Console.WriteLine("Methods are equal?\t\t{0}", m1 == m2);
        Console.WriteLine("Method handles are equal?\t{0}", m1.MethodHandle == m2.MethodHandle);

        Console.WriteLine("Done.");
        Console.ReadKey();
    }
}

(try it online 在 ideone)

因此,有两个不相等的 MethodInfo 实例,它们都包含相同的方法句柄。这是 the equals operator source :

public static bool operator ==(MethodInfo left, MethodInfo right)
{
    if (ReferenceEquals(left, right))
        return true;

    if ((object)left == null || (object)right == null ||
        left is RuntimeMethodInfo || right is RuntimeMethodInfo) // <----??? 
    {
        return false;
    }
    return left.Equals(right);
}

它看起来不像是一个意外错误,至少在假设 RuntimeMethodInfo 的所有实例都被缓存并且同一方法将有两个不同的实例之前是这样。在那种情况下,显然有什么东西坏了。

这种行为背后有什么原因吗?

附言请不要标记为 :) 问题不是关于“如何比较?”。这个问题被多次回答,herehere例如。

谢谢!

最佳答案

我相信您对其背后推理的假设 - 两个 RuntimeMethodInfo 实例可以通过引用相等性进行比较 - 是正确的。不过,您认为它已损坏的假设并不正确。

这里的两个 MethodInfo 对象不同的,因为它们具有不同的 ReflectedType 属性:

Console.WriteLine(m1.ReflectedType); // Program+A
Console.WriteLine(m2.ReflectedType); // Program+B

关于c# - RuntimeMethodInfo 相等 : bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27645408/

相关文章:

c# - Eazfuscator.NET 破坏了 Enum.IsDefined

c# - Assembly.LoadFrom 是否保留打开的文件句柄?

c# - BlockingSenderDestination.sendReceive() UTF-8 问题

c# - 如何隐藏快速访问工具栏中的按钮?

c# - LINQ:给定一个对象列表,创建一个以子对象为键、以父对象为值的字典

c# - Windows 货币符号

c# - VB.NET 和 C# 中的面向对象编程

reflection - 枚举反射

Java通过反射访问私有(private)属性

c# - WCF 错误 'There was an error while trying to serialize parameter...'