Razor Syntax & Data Types
I'm not sure if it's different when us开发者_高级运维ing Razor or not, and I can't find it in the MSDN Docs yet. Is it valid to do something like this?
string f;
foreach(string something in otherthing)
{
f = something.Name;
}
<p>@f</p>
The part that relates to my question is string f;
I know that you cannot declare a var without assigning to it at the same time, but what about String's? And where abouts would I find this type of info?
And why do all the websites (MSDN, MANY tutorials online) always seem to use var instead of string? Is it pure laziness? Is there a real point in using it (instead of)?
The reason I ask why they use var instead of String/string is because in cases where the value clearly is a String, they still use a var. Is it easier to convert vars to another type?
You may declare a string
without assingning it to anything. You cannot do this with var
s because C# must know the type of a var when it is declared, because C# is a statically typed language.
When the compiler sees var s = "string"
, it sees that what is declared is a string and interprets that var
as a string.
If the type can easily be inferred, it is more concise and sometimes more readable to declare a variable using var
instead of an explicit type, such as string
.
Worth checking out Scott Gu's posts on the razor views as he covers most thing on there:
http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx
Also if you haven't seen it yet the ability to use dynamic types with Razor is pretty neat and can be used with things like the postal library
Interesting read: http://aboutcode.net/2010/11/17/going-postal-generating-email-with-aspnet-mvc-view-engines.html
精彩评论