samedi 21 décembre 2019

Dynamic throws RuntimeBinderException although the property exists

I am having a weird situation where I have a RuntimeBinderException thrown when trying to access a property although I know for sure it exists (and the debugger shows so):

enter image description here

The dictionary is Dictionary<int, CraftData>. However, the type is from a loaded Assembly through Reflection so I cannot cast directly. According to the exception, it seems value is still being treated as object (I tried dynamic value = item.Value but it didn't work too).

Weirdly enough, I try to reproduce it in a new project but there is no exception:

class Program
{
    static void Main(string[] args)
    {
        // This works
        var objFromReflection = (object) new Foo();
        var dyn = objFromReflection as dynamic;
        Console.WriteLine(dyn.KnownProperty);

        // This also works but it does not work the same in my project
        IDictionary dictFromReflection = new Dictionary<int, Foo>() { { 1, new Foo() }, { 2, new Foo() } };
        foreach (DictionaryEntry item in dictFromReflection)
        {
            var key = (int)item.Key;
            var value = item.Value as dynamic;
            Console.WriteLine($"{key}: {value.KnownProperty}");
        }
    }
}

class Foo
{
    public string KnownProperty { get; set; } = "A";
    public string OtherProperty1 { get; set; }
    public string OtherProperty2 { get; set; }
}

So my questions:

  • Why does my standalone code work but the real one above does not?

  • Is there anyway to get craftAmount without using Reflection?

My current workaround:

  • Use Reflection to get the property value.

  • Use JsonConvert and use JObject (I know this is dumb).





Aucun commentaire:

Enregistrer un commentaire