params object[] 用于函数多参数的定义
public static void Write(string format, params object[] arg);
 
例如,在下面的示例中,此运算符将名为 Fahrenheit 的类转换为名为 Celsius 的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace EventDemo
{
    class Celsius
    {
        private float degrees;
        public Celsius(float temp)
        {
            degrees = temp;
        }
        public static explicit operator Fahrenheit(Celsius c)
        {
            return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
        }
        public float Degrees
        {
            get { return degrees; }
        }
        
    }

    class Fahrenheit
    {
        private float degrees;
        public Fahrenheit(float temp)
        {
            degrees = temp;
        }
        // Must be defined inside a class called Fahrenheit:
        public static explicit operator Celsius(Fahrenheit fahr)
        {
            return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32));
        }
        public float Degrees
        {
            get { return degrees; }
        }
        
    }

    class Program
    {
        static void Main()
        {
            Fahrenheit fahr = new Fahrenheit(100.0f);
            Console.Write("{0} Fahrenheit", fahr.Degrees);
            Celsius c = (Celsius)fahr;

            Console.Write(" = {0} Celsius", c.Degrees);
            Fahrenheit fahr2 = (Fahrenheit)c;
            Console.WriteLine(" = {0} Fahrenheit", fahr2.Degrees);
            Console.ReadLine();
        }
    }
}
View Code

 

如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace EventDemo
{
    class Digit
    {
        public Digit(double d) { val = d; }
        public double val;
        // ...other members
        // User-defined conversion from Digit to double
        public static implicit operator double(Digit d)
        {
            return d.val;
        }
        //  User-defined conversion from double to Digit
        public static implicit operator Digit(double d)
        {
            return new Digit(d);
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Digit dig = new Digit(7);
            //This call invokes the implicit "double" operator
            double num = dig;
            //This call invokes the implicit "Digit" operator
            Digit dig2 = 12;
            Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
            Console.ReadLine();
        }
    }
}
View Code

相关文章:

  • 2021-07-20
  • 2021-10-14
  • 2021-10-08
  • 2021-07-25
  • 2021-10-30
  • 2022-12-23
猜你喜欢
  • 2022-02-26
  • 2021-10-19
  • 2021-12-12
  • 2022-12-23
  • 2022-01-17
  • 2022-12-23
  • 2021-12-22
相关资源
相似解决方案