You can specify how your type is converted to other types and, equally, how other types are converted to
your type, by declaring conversion operators in your class. A conversion operator is a static method that
is named for the type that you wish to convert to and that has the type you wish to convert from. For
example, the following method fragment is a conversion operator from the myClass type that converts
an instance of string to an instance of myClass (String TO myClass):
public static explicit operator myClass(string str){return new myClass(){this.Text = str};}
Defining this member in the myClass class allows us to perform conversions such as the following:
myClass C1 = (myClass)"Hello";
Note that we have had to explicitly cast the string to myClass—this is because our conversion operator
included the explicit keyword. You can enable implicit conversion by using the implicit keyword, such
as this:
public static implicit operator myClass(string str){return new myClass(){this.Text = str};}
With the implicit keyword, now both of the following statements would compile:
myClass C1 = (myClass)"Hello";myClass C2 = "Hello";
Conversion operators must always be static, and you must choose between an explicit and an
implicit conversion—you cannot define different conversion operators for the same pair of types but
with different keywords.
No comments:
Post a Comment