Is this a hole in dynamic binding in C# 4?

后端 未结 1 590
北海茫月
北海茫月 2021-01-19 02:56

I\'ve seen a very interesting post on Fabio Maulo\'s blog. Here\'s the code and the bug if you don\'t want to jump to the url. I defined a new generic class like so:
<

相关标签:
1条回答
  • 2021-01-19 03:35

    The binder tries to work out an accessible class to treat the object as - in this case, the code making that call doesn't "know" about the MyClass class, so it doesn't "know" about PartitionKey either.

    I don't know how thoroughly this is documented in the C# 4 spec - I know I've had an email conversation about it with Chris Burrows though, so the details may be somewhere on his blog :) Bear in mind that the dynamic binding has changed over time, so more recent posts are likely to be more accurate with respect to the RTM code.

    I think that if you put PartitionKey into a public interface that the private class implements, that may work - but you'd have to try it.

    There are various "gotchas" around dynamic typing. Explicit interface implementation has a similar problem:

    public int Count(IList list)
    {
       int count1 = list.Count; // Fine
       dynamic d = list;
       int count2 = d.Count; // Should work, right?
    }
    

    This will fail if you pass in an array - because although IList.Count exists, it's implemented explicitly in arrays - so it's a bit like this:

    string[] array = new string[10];
    Console.WriteLine(array.Count); // Won't compile
    

    The binder tries to treat the object as its concrete type, not as IList, hence the failure...

    0 讨论(0)
提交回复
热议问题