Cast operator overloading and (c #)

 

http://www.cnblogs.com/chenxizhang/archive/2008/09/14/1290735.html

 

Perhaps you have never considered the issue cast and operator overloading, after all, in many cases, we are the type of system standards, using the built-in conversion of some functions and operators.

But suppose you regularly need to create a custom type (or structure), and you want them all to achieve richer effect, so understanding .NET supports operator overloading and type conversion on a bit necessary

Let's look at the definition of a structure

    public struct MyStruct
    {
        public string Name;

        /// <summary>
        /// This is an operator overloading, but his role is to make the type of conversion, but is implicit type conversion (Implicit)
        /// This is operator specific meaning may be converted into a target string
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        static public implicit operator MyStruct(string s) {
            return MyStruct.Parse(s);
        }

        /// <summary>
        /// manually write a processor (the Parse) functions, showing an object from another format to
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        static public MyStruct Parse(string s)
        {
            MyStruct m = new MyStruct();
            m.Name = s;
            return m;
        }

        /// <summary>
        /// override object of this method is to use a string that represents an object
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return string.Format("Name:{0}", Name);
        }
    }
Let's look at how to use the program
    class Program
    {
        static void Main(string[] args)
        {
            MyStruct m = "Test"; // new structure may not be required to use (when performing phrase, call static public implicit operator MyStruct (string s) Method)
             Console.Write(m);
            Console.Read();
        }
    }

Reproduced in: https: //www.cnblogs.com/lanchong/archive/2011/12/14/2287375.html

Guess you like

Origin blog.csdn.net/weixin_34117211/article/details/94705013