Is there a way to test if a variable is dynamic?

前端 未结 5 1667
北荒
北荒 2020-12-18 18:26

The following piece of code will always return true unless the variable v is null:

v is dynamic

and the following

5条回答
  •  温柔的废话
    2020-12-18 19:23

    There will always be a run-time type as others have said.

    There is a hack to detect for local variables, relying on the fact that dynamic variables doesn't support extension methods.

    static void DummyDynamicTest(this T t) //extension method
    {
    
    }
    
    dynamic test = 1;
    try
    {
        test.DummyDynamicTest();
        //not dynamic
    }
    catch (RuntimeBinderException)
    {
        //dynamic
    }
    

    However you can't refactor the functionality into another method. This can't be very useful at all in any meaningful scenarios, ignore at any cost.

提交回复
热议问题