var 是否比显式类型变量占用更多资源?
Is var more resource intensive than explicitly typed variables?
所以我和我的一些同事正在研究 var 的用法以及我们 should/shouldn 不使用它的原因。
我想知道 var 是否比显式类型变量占用更多资源?
根据我的理解,它只是一个非常动态的变量,并且会(行为相同/使用相同数量的资源)与传递给 var 的类型的任何其他显式类型变量。
能否请对此问题有更多了解的人详细说明?
提前致谢!
Var 只是用于显式写出类型的语法糖。它为您节省了一些输入,也意味着如果您更改分配类型,那么您不需要更新您的变量声明。
例如,如果您有以下代码:
var s = "My String";
String t = "My String";
然后使用 ILSpy 反编译它 s
最初声明为 var
的事实丢失了。当编译器生成 IL 时,它意识到变量 s 是一个字符串,因此将 var
替换为 String
。
隐式类型局部变量的强类型是在编译时确定的,因此在运行时对应用程序性能的影响为零。
var
关键字简化了开发人员必须在变量声明中键入完整对象名称的任务,除此之外别无其他。
It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.
- Implicitly Typed Local Variables (C# Programming Guide)
using System;
namespace ConsoleApp
{
class Program
{
static void Main()
{
var stringImplicit = "Blah";
string stringExplicit = "Blah";
Console.WriteLine("IMPLICIT : {0} - {1}", stringImplicit, stringImplicit.GetType().Name);
Console.WriteLine("EXPLICIT : {0} - {1}", stringExplicit, stringExplicit.GetType().Name);
Console.ReadKey();
}
}
}
你可以看到他们无论如何都变得一样了。如果您查看 IL(中间语言 - 编译代码),您会看到完全相同的 "bytecode"。您所做的只是要求编译器解决它。编译完成后,'effort' 计算类型的方法不再存在。
所以我和我的一些同事正在研究 var 的用法以及我们 should/shouldn 不使用它的原因。
我想知道 var 是否比显式类型变量占用更多资源?
根据我的理解,它只是一个非常动态的变量,并且会(行为相同/使用相同数量的资源)与传递给 var 的类型的任何其他显式类型变量。
能否请对此问题有更多了解的人详细说明?
提前致谢!
Var 只是用于显式写出类型的语法糖。它为您节省了一些输入,也意味着如果您更改分配类型,那么您不需要更新您的变量声明。
例如,如果您有以下代码:
var s = "My String";
String t = "My String";
然后使用 ILSpy 反编译它 s
最初声明为 var
的事实丢失了。当编译器生成 IL 时,它意识到变量 s 是一个字符串,因此将 var
替换为 String
。
隐式类型局部变量的强类型是在编译时确定的,因此在运行时对应用程序性能的影响为零。
var
关键字简化了开发人员必须在变量声明中键入完整对象名称的任务,除此之外别无其他。
It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type. - Implicitly Typed Local Variables (C# Programming Guide)
using System;
namespace ConsoleApp
{
class Program
{
static void Main()
{
var stringImplicit = "Blah";
string stringExplicit = "Blah";
Console.WriteLine("IMPLICIT : {0} - {1}", stringImplicit, stringImplicit.GetType().Name);
Console.WriteLine("EXPLICIT : {0} - {1}", stringExplicit, stringExplicit.GetType().Name);
Console.ReadKey();
}
}
}
你可以看到他们无论如何都变得一样了。如果您查看 IL(中间语言 - 编译代码),您会看到完全相同的 "bytecode"。您所做的只是要求编译器解决它。编译完成后,'effort' 计算类型的方法不再存在。