C#intellisense对于采用动态参数的方法不正确 [英] C# intellisense incorrect for method that takes a dynamic argument
问题描述
考虑遵循简单的课程
public class SomeType
{
public static int Fn(dynamic arg) { return 1; }
}
和关注声明
dynamic value = 10;
var a = SomeType.Fn(null);
var b = SomeType.Fn(value);
a的类型正确(int)
the type of a is correct ( int )
b的类型错误(动态)
the type of b is wrong ( dynamic )
直到对原本已返回整数的原型进行虚拟重铸(int)SomeType.Fn(value)之前,我再不能在b上使用智能感知了.
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 ?
当前的解决方法如下
var b = SomeType.Fn((object)value);
推荐答案
有一种简单的方法可以检查这是否是Intellisense错误:调用 int
不可用的方法.如果编译器为变量指定 int
类型,则会出现编译时错误.如果编译器为变量提供 dynamic
类型,则会出现运行时错误.
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();
如果尝试此操作,则会发现只有 a.DoesNotExist()
会导致编译时错误.
If you try this, you'll find that only a.DoesNotExist()
causes a compile-time error.
换句话说,您看到的Intellisense行为与编译器的行为完全匹配,即涉及 dynamic
参数的方法调用具有 dynamic
结果.
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.
您的解决方法不是解决方法,而是解决方法.如果具有动态类型,则要求编译器确保表达式在运行时已解析.强制转换为 object
时,将删除 dynamic
类型,此时编译器将再次在编译时完全解析该表达式.
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.
这篇关于C#intellisense对于采用动态参数的方法不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!