第七章 运算符和类型强制转换

SimpleCurrency

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

namespace SimpleCurrency
{
    class Program
    {
           struct Currency
           {
              public uint Dollars;
              public ushort Cents;

              public Currency(uint dollars, ushort cents)
              {
                 this.Dollars = dollars;
                 this.Cents = cents;
              }

              public override string ToString()
              {
                 return string.Format("${0}.{1,-2:00}", Dollars,Cents);
              }

              public static implicit operator float(Currency value)
              {
                  return value.Dollars + (value.Cents / 100.0f);
              }

              public static explicit operator Currency(float value)
              {
                  uint dollars = (uint)value;
                  ushort cents = (ushort)((value - dollars) * 100);
                  return new Currency(dollars, cents);
              }

           }

        static void Main(string[] args)
        {
           try
           {
              Currency balance = new Currency(50,35);

              Console.WriteLine(balance);
              Console.WriteLine("balance is " + balance);
              Console.WriteLine("balance is (using ToString()) " + balance.ToString());

              float balance2= balance;

              Console.WriteLine("After converting to float, = " + balance2);

              balance = (Currency) balance2;

              Console.WriteLine("After converting back to Currency, = " + balance);
              Console.WriteLine("Now attempt to convert out of range value of " +
                                "-$50.50 to a Currency:");

              checked
              {
                 balance = (Currency) (-50.50);
                 Console.WriteLine("Result is " + balance.ToString());
              }
           }
           catch(Exception e)
           {
              Console.WriteLine("Exception occurred: " + e.Message);
           }

           Console.ReadLine();
        }
    }
}

SimpleCurrency2

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

namespace SimpleCurrency
{
    class Program
    {
        struct Currency
        {
            public uint Dollars;
            public ushort Cents;

            public Currency(uint dollars, ushort cents)
            {
                this.Dollars = dollars;
                this.Cents = cents;
            }

            public override string ToString()
            {
                return string.Format("${0}.{1,-2:00}", Dollars, Cents);
            }

            public static implicit operator float(Currency value)
            {
                return value.Dollars + (value.Cents / 100.0f);
            }

            public static explicit operator Currency(float value)
            {
                uint dollars = (uint)value;
                ushort cents = (ushort)((value - dollars) * 100);
                return new Currency(dollars, cents);
            }

            public static implicit operator Currency(uint value)
            {
                return new Currency(value, 0);
            }

            public static implicit operator uint(Currency value)
            {
                return value.Dollars;
            }

        }

        static void Main(string[] args)
        {
            try
            {
                   Currency balance = new Currency(50,35);

                   Console.WriteLine(balance);
                   Console.WriteLine("balance is " + balance);
                   Console.WriteLine("balance is (using ToString()) " + balance.ToString());                    

                   float balance2 = balance;

                   Console.WriteLine("After converting to float, = " + balance2);

                   balance = (Currency)balance2;

                   Console.WriteLine("After converting back to Currency, = " + balance);
                   Console.WriteLine("Now attempt to convert out of range value of " +
                                     "-$50.50 to a Currency:");

                checked
                {
                    balance = (Currency)(-50.50);
                    Console.WriteLine("Result is " + balance.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: " + e.Message);
            }

            Console.ReadLine();
        }
    }
}

VectorStruct

using System;
using Wrox.ProCSharp.OOCSharp;

namespace VectorStruct
{
    internal class MainEntryPoint
    {
        private static void Main()
        {
            Vector vect1, vect2, vect3;

            vect1 = new Vector(3.0, 3.0, 1.0);
            vect2 = new Vector(2.0, -4.0, -4.0);
            vect3 = vect1 + vect2;

            Console.WriteLine("vect1 = " + vect1.ToString());
            Console.WriteLine("vect2 = " + vect2.ToString());
            Console.WriteLine("vect3 = " + vect3.ToString());

            Console.ReadLine();
        }
    }
}

namespace Wrox.ProCSharp.OOCSharp
{
    struct Vector
    {
        public double x, y, z;

        public Vector(double x, double y, double z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public Vector(Vector rhs)
        {
            x = rhs.x;
            y = rhs.y;
            z = rhs.z;
        }

        public override string ToString()
        {
            return "( " + x + " , " + y + " , " + z + " )";
        }

        public static Vector operator +(Vector lhs, Vector rhs)
        {
            Vector result = new Vector(lhs);
            result.x += rhs.x;
            result.y += rhs.y;
            result.z += rhs.z;

            return result;
        }
    }
}

VectorStructMoreOverloads

using System;
using Wrox.ProCSharp.OOCSharp;

namespace VectorStruct
{
    internal class MainEntryPoint
    {
        private static void Main()
        {
            // stuff to demonstrate arithmetic operations
            Vector vect1, vect2, vect3;
            vect1 = new Vector(1.0, 1.5, 2.0);
            vect2 = new Vector(0.0, 0.0, -10.0);

            vect3 = vect1 + vect2;

            Console.WriteLine("vect1 = " + vect1);
            Console.WriteLine("vect2 = " + vect2);
            Console.WriteLine("vect3 = vect1 + vect2 = " + vect3);
            Console.WriteLine("2*vect3 = " + 2 * vect3);

            vect3 += vect2;

            Console.WriteLine("vect3+=vect2 gives " + vect3);

            vect3 = vect1 * 2;

            Console.WriteLine("Setting vect3=vect1*2 gives " + vect3);

            double dot = vect1*vect3;

            Console.WriteLine("vect1*vect3 = " + dot);

            Console.ReadLine();
        }
    }
}

namespace Wrox.ProCSharp.OOCSharp
{
    struct Vector
    {
        public double x, y, z;

        public Vector(double x, double y, double z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public Vector(Vector rhs)
        {
            x = rhs.x;
            y = rhs.y;
            z = rhs.z;
        }

        public override string ToString()
        {
            return "( " + x + " , " + y + " , " + z + " )";
        }

        public static Vector operator +(Vector lhs, Vector rhs)
        {
            Vector result = new Vector(lhs);
            result.x += rhs.x;
            result.y += rhs.y;
            result.z += rhs.z;

            return result;
        }

        public static Vector operator *(double lhs, Vector rhs)
        {
            return new Vector(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z);
        }

        public static Vector operator *(Vector lhs, double rhs)
        {
            return rhs * lhs;
        }

        public static double operator *(Vector lhs, Vector rhs)
        {
            return lhs.x * rhs.x + lhs.y + rhs.y + lhs.z * rhs.z;
        }

    }
}

时间: 2024-10-28 21:43:16

第七章 运算符和类型强制转换的相关文章

【读书笔记】C#高级编程 第七章 运算符和类型强制转换

(一)运算符 类别 运算符 算术运算符 + - * / % 逻辑运算符 & | ^ ~ && || ! 字符串连接运算符 + 增量和减量运算符 ++ -- 移位运算符 << >> 比较运算符 == != < > <= >= 赋值运算符 = += -= *= /= %= &= |= ^= <<= >>= 成员访问运算符(用于对象和结构) . 索引运算符(用于数组和索引器) [] 类型转换运算符 () 条件

《C#高级编程》【第7章】运算符与类型强制转换 -- 学习笔记

       运算符编程语言的基本元素,它使得我们的代码更加的简洁明了.然而我们为了解决操作数类型不同的问题,我们又有引入了强制转换的概念.我们先看看本章的内容构成吧. 1.运算符 我们来看看一些常见的运算符: <1>条件运算符 其语法如下: Condition ? true_Expression : false_Expression 当条件Condition为真时,其将执行true_Expression,否则执行false_Expression. <2> checked 和

java三元运算符与类型强制转换

public class yunsuanfu { public static void main(String[] args) { int a = 5; System.out.println("value is "+((a<5) ? 10.9 : 9)); } } 刚刚看到的一道面试题,第一眼看很简单,就一个三元运算符,如果你觉得输出的结果是9,那就中了这道题的陷阱了,注意下"((a<5) ? 10.9 : 9)",里面有一个10.9,而后面跟了一个9,

C# 运算符和类型强制转换(6) 持续更新

C#支持的运算符 https://msdn.microsoft.com/zh-cn/library/6a71f45d(v=vs.140).aspx checked 和 unchecked byte b = 255; b++; Console.WriteLine(b); byte数据类型 范围 0~255.递增 b 的值会导致溢出.CLR如何处理这个溢出取决于很多因素,包括编译器选项. 可以使用代码块标记 checked,发生溢出,抛出 OverflowException 异常. byte b =

PHP类型转换&amp;&amp;类型强制转换

获取数据类型 : 如果想查看某个表达式的值和类型,用 var_dump(). 如果只是想得到一个易读懂的类型的表达方式用于调试,用 gettype(). 要查看某个类型,不要用 gettype(),而用 is_type() 函数. ■字符串转换为数值 当一个字符串被当作数字来求值时,根据以下规则来决定结果的类型和值. 如果包括“.”,“e”或“E”其中任何一个字符的话,字符串被当作 float 来求值.否则就被当作整数. 该值由字符串最前面的部分决定.如果字符串以合法的数字数据开始,就用该数字作

使用 as 和 is 运算符安全地进行强制转换

由于对象是多态的,因此基类类型的变量可以保存派生类型. 若要访问派生类型的方法,需要将值强制转换回该派生类型. 不过,在这些情况下,如果只尝试进行简单的强制转换,会导致引发 InvalidCastException 的风险. 这就是 C# 提供 is 和 as 运算符的原因. 您可以使用这两个运算符来测试强制转换是否会成功,而没有引发异常的风险. 通常,as 运算符更高效一些,因为如果可以成功进行强制转换,它会实际返回强制转换值. 而 is 运算符只返回一个布尔值. 因此,如果只想确定对象的类型

C语言类型强制转换

C语言类型强制转换 强制类型转换是通过类型转换运算来实现的.其一般形式为: (类型说明符) (表达式) 其功能是把表达式的运算结果强制转换成类型说明符所表示的类型. 目录 1基本介绍 2注意事项 1基本介绍编辑 强制类型转换是通过类型转换运算来实现的.其一般形式为:(类型说明符)(表达式)其功能是把表达式的运算结果强制转换成类型说明符所表示的类型.自动转换是在源类型和目标类型兼容以及目标类型广于源类型时发生一个类型到另一类的转换.例如: (float) a 把a转换为实型,(int)(x+y)

OC中的类型强制转换

在Objective-C中,以数字格式组成的字符串经常需要转换为NSNumber对象后再使用.例如有一个字符串对象@"111.22",需要转为NSNumber对象,最简单的方法就是这样:[NSNumber numberWithFloat:[@"111.22" floatValue]]. 这个方法先使用NSString的floatValue方法将字符串转成float,再使用NSNumber的numberWithFloat方法将结果转成NSNumber.但它有一个前提条

字符格式化输出,类型强制转换,点访问数据属性,

name = input("Name:") age = int(input("Age:"))       #类型强制转换 job = input("Job:") salary = input("Salary:") if salary.isdigit():                 #  .isdigit()用于判断数据是不是数字 salary = int(salary) msg = ''' ----------info