用户自定义转换 除了标准转换,我们还可以为类和结构定义隐式和显式转换。 除了implicit和explicit关键字之外,隐式和显示转换声明语法是一样的! 需要public和static修饰符。 格式如下: public static implicit operator TargetType(SourceType Identifiler)//隐式或显示 {... return objectTargetType;} 用户自定义转换有些约束 1.只可以为类和结构定义用户自定义转换。 2.不能重定义标准隐式转换和显示转换 对于源类型S和目标类型T,如下命题为真。 1.S和T必须是不同的类型 2.S和T不能通过继承关联,也就是说S不能继承自T,T也不能继承自S 3.S和T都不能是接口类型或object类型。 4.转换运算符必须是S或T的成员。 对于相同的源类型和目标类型,我们不能声明隐式转换和显示转换。
namespace ConsoleApplication1 { public class person { public string name; public int age; public person(string name,int age) {this.name=name; this.age=age; } public static implicit operator int(person p)//将person转换为int {return p.age; } public static implicit operator person(int i)//将int转换为person {return new person("雷江涛",i); } } class Program { static void Main(string[] args) {person bill=new person ("曹静",25); int age=bill;//把person转换为int; Console.WriteLine("{0}, {1}",bill.name ,age); person anon = 23;//把int转换为person Console.WriteLine("{0}, {1}", anon.name, anon.age); Console.ReadLine(); } } }
public static explicit operator int(person p)//将person转换为int {return p.age; } public static explicit operator person(int i)//将int转换为person {return new person("雷江涛",i); } int age = (int)bill;//错误无法将类型“ConsoleApplication1.person”隐式转换为“int”。存在一个显式转换(是否缺少强制转换?) person anon =(person)23;//错误无法将类型“int”隐式转换为“ConsoleApplication1.person”。存在一个显式转换(是否缺少强制转换?)
如果使用explicit运算符而不是impicit来定义相同的转换,需要使用强制转换运算表达式来进行转换。
还有一些转换:评估用户自定义转换以及多步用户自定义转换,这儿就不说了!!!is运算符来检查转换是否会成功完成,as运算符类似,只不过他们的共同特点是不会抛出异常的!
原文:http://www.cnblogs.com/leijiangtao/p/4155330.html