C# intellisense incorrect for method that takes a dynamic argument

守給你的承諾、 提交于 2021-01-27 23:45:39

问题


consider follow simple class

public class SomeType
{
    public static int Fn(dynamic arg) { return 1; }            
}

and the follow statement

dynamic value = 10;
var a = SomeType.Fn(null);
var b = SomeType.Fn(value);

the type of a is correct ( int )

the type of b is wrong ( dynamic )

I can't use intellisense any more on b until I do a dummy recast (int)SomeType.Fn(value) for what was already prototype to return an integer.

the question is, why the dynamic in the argument makes the intellisense to change my function prototype signature ?

even if I insert a dynamic into a function, that function cannot return nothing else than what is declared in its prototype, is this a bug ?

current workaround for me is the following

var b = SomeType.Fn((object)value);

回答1:


There is an easy way to check whether this is an Intellisense bug: call a method that is not available for int. If the compiler gives the variable the type int, you'll get a compile-time error. If the compiler gives the variable the type dynamic, you'll get a run-time error.

dynamic value = 10;
var a = SomeType.Fn(null);
a.DoesNotExist();
var b = SomeType.Fn(value);
b.DoesNotExist();

If you try this, you'll find that only a.DoesNotExist() causes a compile-time error.

In other words, the Intellisense behaviour you're seeing perfectly matches the compiler's behaviour, which is that a method call involving dynamic arguments has a dynamic result.

Your workaround isn't a workaround, it's a fix. When you have dynamic types, you're asking the compiler to ensure the expression is resolved at run-time. When you cast to object, you're taking the dynamic types out, and at that point the compiler will fully resolve the expression at compile-time again.



来源:https://stackoverflow.com/questions/39551475/c-sharp-intellisense-incorrect-for-method-that-takes-a-dynamic-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!