简体   繁体   English

“var”如何在不指定命名空间的情况下工作?

[英]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.

相关问题 如何在不指定名称空间的情况下从字段中消除枚举的歧义? - How do I disambiguate enums from fields without specifying the namespace? 即使不指定模型类型,MVC View如何工作? - How MVC View works even without specifying Model type? 解析XDocument而不必继续指定默认命名空间 - Parse XDocument without having to keep specifying the default namespace 为什么Redis连接可以在C#中工作而无需指定凭据? - Why Redis connection works from C# without specifying credentials? C#重载键/值和非键/值类型,使用var而不指定类型 - C# overload key/value and non key/value type , using var without specifying type 指定具体类型而不是var - Specifying concrete types instead of var 为什么我可以访问一个类,而无需为其指定包含的命名空间 - C# - Why am I able to access a class, without specifying the containing namespace for it - C# 我可以导入一个 static class 作为命名空间来调用它的方法而不在 ZD7EFA19FBE7D3972FDZ5ADB6 中指定 class 名称吗? - Can I import a static class as a namespace to call its methods without specifying the class name in C#? 我的Outlook加载项怎么只能一次使用? - How come my outlook add-in only works once? 这种从递归到迭代的转换是如何神奇地起作用的? - How come this conversion from recursion to iteration magically works?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM