You can define conversion operators to specify how your type is converted to other types and how other types are converted to your type.
The following method fragment is a conversion operator from the Text type that converts an instance of string to an instance of Text:
public static explicit operator Text(string str)
{
return new Word() { MyString = str };
}
We can use the explicit operator as the following:
Text text = (Text)"abc";
We have had to explicitly cast the string to Text
, 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 Text(string str)
{
return new Text() { MyString = str };
}
With the implicit keyword, now both of the following statements would compile:
Text text = (Text)"Hello";
Text text = "Hello";
Conversion operators must always be static
.
The following example defines and demonstrates implicit and explicit conversion operators for the Text
type.
using System;
public class Text
{
public string MyString
{
get;
set;
}
public static explicit operator Text(string str)
{
return new Text() { MyString = str };
}
public static implicit operator string(Text w)
{
return w.MyString;
}
public static explicit operator int(Text w)
{
return w.MyString.Length;
}
public override string ToString()
{
return MyString;
}
}
public class MainClass
{
static void Main(string[] args)
{
Text word1 = new Text() { MyString = "Hello" };
// Implicitly convert the word to a string.
string str1 = word1;
// Explicitly convert the word to a string.
string str2 = (string)word1;
Console.WriteLine("{0} - {1}", str1, str2);
// Convert a string to a word.
Text word2 = (Text)"Hello";
// Convert a word to an int.
int count = (int)word2;
Console.WriteLine("Length of {0} = {1}", word2.ToString(), count);
}
}
The output:
Hello - Hello
Length of Hello = 5
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |