Csharp/C Sharp/Data Types/cast — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 18:31, 26 мая 2010

Any object, value, or reference type that is convertible to an integral, char, enum, or string type is acceptable as the switch_expression

<source lang="csharp"> using System; class Employee {

   public Employee(string f_Emplid) {
       m_Emplid = f_Emplid;
   }
   static public implicit operator string(Employee f_this) {
       return f_this.m_Emplid;
   }
   private string m_Emplid;

} class Starter {

   static void Main() {
       Employee newempl = new Employee("1234");
       switch (newempl) {
           case "1234":
               Console.WriteLine("Employee 1234");
               return;
           case "5678":
               Console.WriteLine("Employee 5678");
               return;
           default:
               Console.WriteLine("Invalid employee");
               return;
       }
   }

}

</source>


Conversions between Simple Types

<source lang="csharp"> using System; public class MainClass {

   public static void Main() {
       double d = 2.9;
       Console.WriteLine((int)d);                   // double-->int; prints 2 
       Console.WriteLine((int)(-d));                // double-->int; prints -2 
       uint seconds = (uint)(24 * 60 * 60);         // int-->uint 
       double avgSecPerYear = 365.25 * seconds;     // I uint-->double 
       float f = seconds;                           // IL uint-->float 
       long nationalDebt1 = 99999999999999;
       double perSecond = 99999.14;
       decimal perDay = seconds * (decimal)perSecond;              // I uint-->decimal 
       double nd2 = nationalDebt1 + (double)perDay; // decimal-->double 
       long nd3 = (long)nd2;                        // double-->long 
       float nd4 = (float)nd2;                      // double-->float 
   }

}

</source>


explicit cast

<source lang="csharp"> using System; class ExplicitConv {

   static void Main() {
       double a = 5.654321;
       int b;
       b = (int)a;
       Console.WriteLine("The value is {0}", b);
   }

}

</source>


Implicit cast

<source lang="csharp"> using System; class ImplicitConversion {

   public static void Main() {
       byte a = 1;
       int b = 1234;
       int c = a; //Implicit cast
       double d = b; //Implicit cast
       Console.WriteLine("{0}", c);
       Console.WriteLine("{0}", d);
   }

}

</source>


Type convert

<source lang="csharp"> /* Type Can Safely Be Converted To Byte short, ushort, int, uint, long, ulong, float, double, decimal Sbyte short, int, long, float, double, decimal Short int, long, float, double, decimal Ushort int, uint, long, ulong, float, double, decimal Int long, float, double, decimal Uint long, ulong, float, double, decimal Long float, double, decimal Ulong float, double, decimal Float double Char ushort, int, uint, long, ulong, float, double, decimal

  • /
</source>