RuntimeMethodInfo equality: error?

Let's start with:

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 on the internet at ideone)

So, there are two unequal instances MethodInfo

, both of which contain the same method descriptor. Here's the source for the equivalent operators :

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);
}

      

This doesn't seem like a random error, at least until it is assumed that all instances RuntimeMethodInfo

are cached and the new one is two different instances for the same method. In this case, obviously, something is violated.

Any reasons for this behavior, anyone?

PS Don't mark it as [duplicate], please :) The question is not "how to compare?" This answer has been answered multiple times, here and here for example.

Thank!

+3


source to share


1 answer


I believe that your assumption about the reasons for this - two instances RuntimeMethodInfo

can be compared for reference equality - is correct. Your assumption that it is broken is incorrect.

The two objects MethodInfo

are different here, as they have different properties ReflectedType

:



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

      

+6


source







All Articles