RuntimeBinderException
In C#, we often need to add new methods to existing classes without modifying the original source code. Extension methods were introduced to meet this need.
Consider a list of integers and access the first element using the First()
method:
List<int> list = new List<int>() { 5, 56, 2, 4, 63, 2 }; Console.WriteLine(list.First());
This code works perfectly. However, if you try to convert the same list into a dynamic object using the dynamic
keyword, an exception is thrown:
dynamic dList = list; Console.WriteLine(dList.First()); // 抛出 RuntimeBinderException
To understand this unusual behavior, we need to have a deep understanding of the underlying mechanism of extension methods. In non-dynamic code, the compiler searches all known classes for a static class that provides a matching extension method. This search follows namespace nesting order and available using
directives.
The dynamic language runtime (DLR) encounters a challenge when calling dynamic extension methods. It must determine at runtime the namespace nesting and using
directives present in the source code. However, there is no convenient mechanism to encode this information into the calling site. While the possibility of designing such a mechanism was considered, it was ultimately deemed too costly and risky to implement.
The above is the detailed content of Why Do Dynamic Extension Methods Throw RuntimeBinderExceptions in C#?. For more information, please follow other related articles on the PHP Chinese website!