一、两个类型之间的强制转型依靠转型操作符(非继承关系)
1 class FirstType 2 { 3 public string Name { get; set; } 4 } 5 6 class SecondType : FirstType 7 { 8 public string Name { get; set; } 9 10 //转型操作符 11 public static explicit operator SecondType(FirstType firstType) 12 { 13 SecondType secondType = new SecondType() { Name = "转型自:" + firstType.Name }; 14 return secondType; 15 } 16 }
FirstType类转型为SecondType类要写转型操作符(转型操作符实际上就是一个方法,类型的转换需要手工写代码完成)。
1 FirstType f = new FirstType() { Name = "First Type" }; 2 SecondType s = (SecondType)f;//转型成功 3 //SecondType s1 = f as SecondType;//编译期转型失败,编译不通过
二、有继承关系的类型转换用as关键字
1 class FirstType 2 { 3 public string Name { get; set; } 4 } 5 6 class SecondType : FirstType 7 { 8 }
1 SecondType s = new SecondType() { Name = "Second Type" }; 2 FirstType f1 = (FirstType)s;//强制转型 3 FirstType f2 = s as FirstType;//as关键字
强制转型和as都可以,但是从效率的角度来看,建议使用as。
as不能操作基元类型,如果涉及基元类型的算法,需要通过is进行转型前判断类型,避免转型失败。
1 static void Main(string[] args) 2 { 3 SecondType s = new SecondType() { Name = "Second Type" 4 }; 5 DoWithSomeType(s); 6 } 7 static void DoWithSomeType(object obj) 8 { 9 if (obj is SecondType)//判断类型 10 { 11 SecondType s = obj as SecondType; 12 } 13 }
参考:《编写高质量代码改善C#程序的157个建议》陆敏技