vendredi 19 janvier 2018

Invoke Equals method on Enum property on class

I have the following setup:

public enum TestEnum
{
    Item1,
    Item2,
    Item3,
    Item4,
    Item5
}

public class Test
{
    public TestEnum TestEn { get; set; }
}

I now what to get the equals method and invoke it:

        var equalsMethod = typeof(TestEnum).GetMethod("Equals");

        Test g = new Test()
        {
            TestEn = TestEnum.Item3
        };

        var r1 = equalsMethod.Invoke(g, new object[] { TestEnum.Item3 });
        var r2 = equalsMethod.Invoke(g, new object[] { 2 });
        var r3 = equalsMethod.Invoke(g, new object[] { (TestEnum)2 });

        var r4 = g.TestEn.Equals(TestEnum.Item3);
        var r5 = g.TestEn.Equals((TestEnum)2);

Using reflection and the invoke call r1, r2 and r3 lines all fail with the following error:

Object does not match the target type.

What can I add to make this work?

I'm effectively looking at doing the same as lines r4 and r5 but using reflection.

Thanks





Aucun commentaire:

Enregistrer un commentaire