user-defined transformations in addition to standard conversions, we can also define implicit and explicit conversions for classes and structs. In addition to the implicit and explicit keywords, the implicit and explicit conversion declaration syntax is the same! The public and static modifiers are required. the format is as follows: Public Static Implicit operatorTargetType (sourcetype Identifiler)//implicit or explicit{... returnObjecttargettype;} user-defined conversions some constraints 1. You can define user-defined transformations only for classes and structs. 2the standard implicit conversion and display transformations cannot be redefined for the source type S and the target type T, as follows the proposition is true. 1. S and T must be of different types2. S and T cannot be associated by inheritance, meaning s cannot inherit from T,t and cannot inherit from S3. Both S and T cannot be interface types or object types. 4 the. Conversion operator must be a member of S or T. We cannot declare implicit conversions and display transformations for the same source and target types.
Namespaceconsoleapplication1{ Public classPerson { Public stringname; Public intAge ; PublicPersonstringNameintAge ) { This. name=name; This. age=Age ; } Public Static Implicit operator int(Person P)//convert person to int{returnP.age; } Public Static Implicit operatorPersonintI//convert int to person{return NewPerson"Reijiangtao", i); } } classProgram {Static voidMain (string[] args) {Person Bill=NewPerson ("Intertek", -); intAge=bill;//converts person to int;Console.WriteLine ("{0}, {1}", Bill.name, age); Person Anon= at;//convert int to personConsole.WriteLine ("{0}, {1}", Anon.name, anon.age); Console.ReadLine (); } }}
Public Static Explicit operator int(Person P)//convert person to int{returnp.age;} Public Static Explicit operatorPersonintI//convert int to person{return NewPerson"Reijiangtao", i);}intAge =(int)Bill//error cannot implicitly convert type "Consoleapplication1.person" to "int". An explicit conversion exists (is there a missing cast?) Person anon =(person) at;//Error cannot implicitly convert type "int" to "Consoleapplication1.person". An explicit conversion exists (is there a missing cast?)
If you use the explicit operator instead of impicit to define the same transformation, you need to use a cast expression to convert it.
There are also conversions: Evaluate user-defined conversions and multi-step user-defined conversions, and here's not the point!!! The IS operator to check if the conversion will be completed successfully, as operators are similar, except that their common feature is not to throw an exception!
User-defined conversions