using Linq with dynamic c# objects
When i run the following code :
var aList = new List<string>{"a", "b", "c"};
dynamic a = aList.Where(item => item.StartsWith("a"));
dynamic b = a.Count();
Microsoft.CSharp.RuntimeBinder.RunTimeBinderException raises.
开发者_运维百科But when I write a code snippet like this:
public interface IInterface
{
}
public class InterfaceImplementor:IInterface
{
public int ID = 10;
public static IInterface Execute()
{
return new InterfaceImplementor();
}
}
public class MyClass
{
public static void Main()
{
dynamic x = InterfaceImplementor.Execute();
Console.WriteLine(x.ID);
}
}
it's work.
Why first code snippet doesn't work?
Because the Count
method is an extension method on IEnumerable<T>
(Once you call Where
, you don't have a list anymore, but an IEnumerable<T>
). Extension methods don't work with dynamic types (at least in C#4.0).
Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload.
Will the dynamic keyword in C#4 support extension methods?
Extension methods are syntactic sugar that allow you to call a static method as if it was a real method. The compiler uses imported namespaces to resolve the correct extension method and that is information the runtime doesn't have. You can still use the extension methods, you just have to call them directly in their static method form like below.
var aList = new List<string>{"a", "b", "c"};
dynamic a = aList.Where(item => item.StartsWith("a"));
dynamic b = Enumerable.Count(a);
精彩评论