How can a dynamic be used as a generic?

前端 未结 6 481
南旧
南旧 2021-01-02 06:08

How can I use a dynamic as a generic?

This

var x = something not strongly typed;
callFunction();

and this

         


        
6条回答
  •  忘掉有多难
    2021-01-02 07:04

    You could use type inference to sort of trampoline the call:

    dynamic x = something not strongly typed;
    CallFunctionWithInference(x);
    
    ...
    
    static void CallFunctionWithInference(T ignored)
    {
        CallFunction();
    }
    
    static void CallFunction()
    {
        // This is the method we really wanted to call
    }
    

    This will determine the type argument at execution time based on the execution-time type of the value of x, using the same kind of type inference it would use if x had that as its compile-time type. The parameter is only present to make type inference work.

    Note that unlike Darin, I believe this is a useful technique - in exactly the same situations where pre-dynamic you'd end up calling the generic method with reflection. You can make this one part of the code dynamic, but keep the rest of the code (from the generic type on downwards) type-safe. It allows one step to be dynamic - just the single bit where you don't know the type.

提交回复
热议问题