您的位置:首页 > Web前端

Item 3: Prefer the is or as Operators to Casts(Effective C#)

2011-01-09 11:16 585 查看
  Remember that user-defined conversion operators operate only on the compile-time type of an object, not on the runtime type.  Now that you know to use as when possible, let’s discuss when you can’t use it. The as operator does not work on value types.   The is operator should be used only when you cannot convert the type using as. Otherwise, it’s simply redundant.  foreach uses a cast operation to perform conversions from an object to the type used in the loop. foreach needs to use casts to support both value types and reference types. By choosing the cast operator, the foreach statement exhibits the same behavior, no matter what the destination type is. However, because a cast is used, foreach loops can cause an InvalidCastException to be thrown. 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Collections;
6
7 namespace EffectiveCSharpItem3
8 {
9 public class MyType
{
}

public class SecondType
{
private MyType type = new MyType();

public static implicit operator MyType(SecondType t)
{
return t.type;
}
}

class Program
{
static void Main(string[] args)
{
SecondType st = new SecondType();
MyType t = (MyType)st;

IEnumerable collection = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var small = from int item in collection
where item < 5
select item;
var small2 = collection.Cast<int>().Where(item => item < 5);
foreach (int i in small)
{
Console.WriteLine(i);
}

foreach (int i in small2)
{
Console.WriteLine(i);
}
Console.WriteLine(t == null);
Console.Read();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐