[英]What is the difference between these two statements (asp.net/c#/entity framework)
IEnumerable<Department> myQuery = (from D in myContext.Departments orderby D.DeptName select D);
var myQuery = (from D in myContext.Departments orderby D.DeptName select D);
What is the difference between these two statements above? 上面的这两个语句有什么区别? In my little asp.net/C#/ EF4.0 app I can write them either way, and as far as how I want to use them, they both work, but there has to be a reason why I would choose one over the other?
在我小的asp.net/C#/ EF4.0应用程序中,我可以用任何一种方式编写它们,而且就我想如何使用它们而言,它们都可以工作,但是必须要有一个理由我选择一个?
The second one is shorter (assuming type of D
is Department
). 第二个较短(假设
D
类型为Department
)。
(actually, the return type of the query may be something other than IEnumerable
, like IQueryable
but the point is, the type will be statically inferred from the right hand side of the assignment operator instead of being explicitly mentioned in code). (实际上,查询的返回类型可能不是
IEnumerable
,而是IQueryable
而不是IEnumerable
,但要指出的是,该类型将从赋值运算符的右侧进行静态推断 ,而不是在代码中明确提及)。
(from D in myContext.Departments orderby D.DeptName select D);
returns an object of type IQueriable<Department>
which in turn implements IEnumerable<Department>
返回类型为
IQueriable<Department>
的对象,该对象又实现IEnumerable<Department>
while you use the var
keyword in here the compiler replace it with IQueriable<Department>
在此处使用
var
关键字时,编译器将其替换为IQueriable<Department>
I believe in the 2nd case the type of myQuery
is an IQueryable<Department>
rather than IEnumerable
. 我相信在
myQuery
情况下, myQuery
的类型是IQueryable<Department>
而不是IEnumerable
。 If you don't need anything specific to an IQueryable that you can't do with an IEnumerable then they behave the same. 如果不需要使用IEnumerable无法实现的IQueryable特定功能,则它们的行为相同。
The var
keyword is just for convenience when the compiler can figure out the type without spelling it out. var
关键字只是为了方便起见,当编译器可以找出类型而不拼写出来时。 So instead of 所以代替
MyReallyLongGenericClassName<SomeOtherType> myObject = new MyReallyLongGenericClassName<SomeOtherType>();
You can just write var myObject = new MyReallyLongGenericClassName<SomeOtherType>();
您可以只写
var myObject = new MyReallyLongGenericClassName<SomeOtherType>();
With var the compiler infers the type of myQuery. 使用var时,编译器会推断出myQuery的类型。 It would probably endup being an
IQueryable<Department>
rather than an IEnumerable<Department>
. 最终可能是
IQueryable<Department>
而不是IEnumerable<Department>
。
The only difference here is that you're not declaring yourself the type of myQuery
. 唯一的区别是您没有声明自己的
myQuery
类型。 You're taking advantage of a feature named Type Inference . 您正在利用名为Type Inference的功能。 Indeed the type returned will be
IQueryable<Department>
where the first statment explicitly types the variable as IEnumerable
. 实际上,返回的类型将是
IQueryable<Department>
,其中第一个语句将变量明确地键入IEnumerable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.