class Program
{
static void Main(string[] args)
{
HelloIHaveALongLongName<string, string> obj = new HelloIHaveALongLongName<string, string>();
}
}
public class HelloIHaveALongLongName<T, T>
{
public string Name;
}
如果使用var关键字,就变成:
var obj = new HelloIHaveALongLongName<string, string>();
obj.Name = "hello";
可见,用var关键字,让写法更简短,并且var变量是一个强类型。
var关键字与匿名类型
通过LINQ表达式返回一个匿名类型。
static void Main(string[] args)
{
string[] strs = {"hello", "world", "nice", "to", "meet", "you"};
object o = from s in strs
where s.Length > 3
select new {s.Length, s};
}
以上,object类型变量o并不是一个强类型变量。
如果我们用强类型的类来接收LINQ返回的集合。
class Program
{
static void Main(string[] args)
{
string[] strs = {"hello", "world", "nice", "to", "meet", "you"};
IEnumerable<SomeData> o = from s in strs
where s.Length > 3
select new SomeData() {Key = s.Length, Value = s};
foreach (SomeData item in o)
{
Console.WriteLine(item.Key);
}
}
}
public class SomeData
{
public int Key;
public string Value;
}
以上,在IEnumerable<SomeData>类型集合中,每一个集合元素都是强类型。
如果用var关键字来接收LINQ返回的匿名类型集合。
class Program
{
static void Main(string[] args)
{
string[] strs = { "hello", "world", "nice", "to", "meet", "you" };
var o = from s in strs
where s.Length > 3
select new { Key = s.Length, Value = s };
foreach (var item in o)
{
Console.WriteLine(item.Key);
}
}
}
class Program
{
static void Main(string[] args)
{
HelloIHaveALongLongName<string, string> obj = new HelloIHaveALongLongName<string, string>();
}
}
public class HelloIHaveALongLongName<T, T>
{
public string Name;
}
如果使用var关键字,就变成:
var obj = new HelloIHaveALongLongName<string, string>();
obj.Name = "hello";
可见,用var关键字,让写法更简短,并且var变量是一个强类型。
var关键字与匿名类型
通过LINQ表达式返回一个匿名类型。
static void Main(string[] args)
{
string[] strs = {"hello", "world", "nice", "to", "meet", "you"};
object o = from s in strs
where s.Length > 3
select new {s.Length, s};
}
以上,object类型变量o并不是一个强类型变量。
如果我们用强类型的类来接收LINQ返回的集合。
class Program
{
static void Main(string[] args)
{
string[] strs = {"hello", "world", "nice", "to", "meet", "you"};
IEnumerable<SomeData> o = from s in strs
where s.Length > 3
select new SomeData() {Key = s.Length, Value = s};
foreach (SomeData item in o)
{
Console.WriteLine(item.Key);
}
}
}
public class SomeData
{
public int Key;
public string Value;
}
以上,在IEnumerable<SomeData>类型集合中,每一个集合元素都是强类型。
如果用var关键字来接收LINQ返回的匿名类型集合。
class Program
{
static void Main(string[] args)
{
string[] strs = { "hello", "world", "nice", "to", "meet", "you" };
var o = from s in strs
where s.Length > 3
select new { Key = s.Length, Value = s };
foreach (var item in o)
{
Console.WriteLine(item.Key);
}
}
}