[英]How come "var" works without specifying the namespace?
I have the following code:我有以下代码:
var dataExistsResult = await _service.CheckifExists(RequestDto);
if (dataExistsResult != null && dataExistsResult.CountProperties() > 0)
//do something
But if i specify "var" PropertiesWithData dataExistsResult = await _service.CheckifExists(RequestDto);
但是如果我指定“var” PropertiesWithData dataExistsResult = await _service.CheckifExists(RequestDto);
it doesn't work since the namespace is not included in the file:它不起作用,因为命名空间不包含在文件中:
namespace Core.Common
{
public class PropertiesWithData
{
I need to set using Core.Common;
我需要using Core.Common;
for that to work.为此工作。 How come "var" is working when running the program?为什么“var”在运行程序时起作用? And how come it possible to access properties of "var" if it knows the type but using Core.Common;
如果它知道类型但using Core.Common;
怎么可能访问“var”的属性? is not in the file?不在文件里? eg: dataExistsResult.CountProperties()
Is Core.Common.PropertiesWithData
added at runtime? eg: dataExistsResult.CountProperties()
Core.Common.PropertiesWithData
是在运行时添加的吗? eg Core.Common.PropertiesWithData dataExistsResult = await _service.CheckifExists(RequestDto);
例如Core.Common.PropertiesWithData dataExistsResult = await _service.CheckifExists(RequestDto);
Namespaces are part of the type name.命名空间是类型名称的一部分。 So when your code refers to a type (by name), it must specify the namespace one way or another.因此,当您的代码(按名称)引用一种类型时,它必须以某种方式指定命名空间。
When using var
, the type is not referred to by name, so no namespace is necessary.使用var
时,类型不是通过名称引用的,因此不需要命名空间。 The compiler knows what type it is because the method declaration includes the type name (including namespace).编译器知道它是什么类型,因为方法声明包括类型名称(包括命名空间)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.