Convert to IEnumerable?

前端 未结 4 1102
别那么骄傲
别那么骄傲 2021-02-14 13:13

I wrote this extension method :

public static class A
{
 public static IEnumerable AsDynamic(this IEnumerable f)
    {
                 


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 14:00

    I think that you have a misunderstanding of what dynamic means. Essentially, when you tell the compiler that an object's type is dynamic, you "promise" that the object at runtime will support whatever methods or properties that you invoke, in exchange for the compiler not complaining at compile time. You also promise that you will face the consequences if you break your promise.

    When you say that an object is dynamic, the compiler cannot make assumptions about the type, so it uses object, knowing that anything can be stored as object. When you make an IEnumerable, it becomes IEnumerable, with one significant difference: you can call any method on its elements, and the compiler will not say a word:

    IEnumerable original = ...
    foreach (dynamic x in original.AsDynamic()) { // Using your method
        Console.WriteLine(x.SomeUnsupportedMethod()); // The compiler is silent!
    }
    

    Since original.AsDynamic() gives a sequence of dynamic objects, the compiler does not complain about your call to SomeUnsupportedMethod. If the method is indeed not supported at runtime, the program will crash; if the method is actually supported by elements of SomeType, there would be no crash, and the method will be invoked.

    That's all the dynamic will do for you; statically, the "placeholder" will remain object, and typeof will tell you as much. But the exact capabilities of the object (its methods and properties) will not be examined until runtime.

    提交回复
    热议问题