[英]keyword “auto” C++ and “dynamic” C#
Does "dynamic" keyword in C# work like "auto" in C++ C# 中的“dynamic”关键字是否像 C++ 中的“auto”一样工作
More details:更多细节:
auto a = 5; //C++
dynamic a = 5; //C#
Are they similar?他们相似吗?
NO, they are not similar.不,它们不相似。 AFAIK,
auto
would be similar to var
in C#. AFAIK,
auto
类似于 C# 中的var
。
auto
gets resolved to compile time, not runtime. auto
被解析为编译时,而不是运行时。
FROM MSDN来自 MSDN
The auto keyword directs the compiler to use the initialization expression of a declared variable to deduce its type.
auto 关键字指示编译器使用已声明变量的初始化表达式来推断其类型。
So in your code所以在你的代码中
auto a = 5; //C++
a.ToUpper(); // Compile time error
But但
dynamic a = 5; //C#
a.ToUpper(); //No error at compile time since it will resolve @ runtime
But at run time it will throw an error since int
type has no ToUpper()
method但是在运行时它会抛出错误,因为
int
类型没有ToUpper()
方法
No.不。
The equivalent of auto
in C# is var
- the compiler will deduce the appropriate type. C# 中
auto
的等价物是var
- 编译器将推导出适当的类型。 dynamic
is determined at runtime, so it will never throw compile errors. dynamic
是在运行时确定的,所以它永远不会抛出编译错误。 From MSDN:来自 MSDN:
"At compile time, an element that is typed as dynamic is assumed to support any operation." “在编译时,假定类型为动态的元素支持任何操作。”
It will however throw errors at runtime if the code is invalid.但是,如果代码无效,它将在运行时抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.