How can a dynamic be used as a generic?

前端 未结 6 459
南旧
南旧 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:02

    It's hard to tell what exactly are you trying to do. But if you want to call a generic method with a type parameter that is the same as some object, you can't do that directly. But you can write another method that takes your object as a parameter, let the dynamic infer the type and then call the method you want:

    void HelperMethod(T obj)
    {
        CallFunction();
    }
    
    …
    
    dynamic x = …;
    HelperMethod(x);
    

提交回复
热议问题