Csharp/C Sharp/Language Basics/Operators — различия между версиями

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

Текущая версия на 11:39, 26 мая 2010

control the operator evaluation sequence

 
using System;
public class MainClass {
    static void Main(string[] args) {
        int a;
        a = -42;
        Console.WriteLine("{0}", a);
        int b = 2;
        int c = 42;
        a = b * (-c);
        Console.WriteLine("{0}", a);
        c = -42;
        a = b * (+c);
        Console.WriteLine("{0}", a);
    }
}


Demonstrates compound assignment operators

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
//  Assign.cs - Demonstrates compound assignment operators
//
//  Compile this program with the following command line:
//           C:>csc Assign.cs
//
namespace nsAssignment
{
    using System;
    
    public class Assign
    {
        static public void Main ()
        {
  unsafe
  {
    int x = sizeof (decimal);
    Console.WriteLine ("sizeof decimial = " + x);
  }
//
//  Start with an integer variable
            int Var = 2;
//
//  Show the starting value
            Console.WriteLine ("At the beginning, Var = {0}", Var);
//
//  Multiply the variable by something
            Var *= 12;
            Console.WriteLine ("After Var *= 12, Var = {0}", Var);
//
//  Add something to the variable
            Var += 42;
            Console.WriteLine ("After Var += 42, Var = {0}", Var);
//
//  Divide the variable by something
            Var /= 6;
            Console.WriteLine ("After Var /= 6, Var = {0}", Var);
//
//  Shift the bits in the variable four spaces to the left
//  This is the same as multiplying by 16 (2 to the fourth power)
            Var <<= 4;
            Console.WriteLine ("After Var <<= 4, Var = {0}", Var);
//
//  Shift the bits in the variable four spaces to the right using
//  and expression on the right. This is the same as dividing
//  by 16.
            int Shift = 3;
            Var >>= Shift + 1;
            Console.WriteLine ("After Var >>= Shift + 1, Var = {0}", Var);
//
//  Modulo divide the variable by something
            Var %= 6;
            Console.WriteLine ("After Var %= 6, Var = {0}", Var);
        }
    }
}


Demonstrate the difference between prefix postfix forms of ++

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* 
   Demonstrate the difference between prefix 
   postfix forms of ++. 
*/ 
using System; 
 
public class PrePostDemo {  
  public static void Main() {    
    int x, y; 
    int i; 
 
    x = 1; 
    Console.WriteLine("Series generated using y = x + x++;"); 
    for(i = 0; i < 10; i++) { 
 
      y = x + x++; // postfix ++ 
 
      Console.WriteLine(y + " "); 
    } 
    Console.WriteLine(); 
 
    x = 1; 
    Console.WriteLine("Series generated using y = x + ++x;"); 
    for(i = 0; i < 10; i++) { 
 
      y = x + ++x; // prefix ++ 
 
      Console.WriteLine(y + " "); 
    } 
    Console.WriteLine(); 
    
  } 
}


Demonstrate the relational and logical operators

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate the relational and logical operators. 
 
using System; 
 
public class RelLogOps {    
  public static void Main() {    
    int i, j; 
    bool b1, b2; 
 
    i = 10; 
    j = 11; 
    if(i < j) Console.WriteLine("i < j"); 
    if(i <= j) Console.WriteLine("i <= j"); 
    if(i != j) Console.WriteLine("i != j"); 
    if(i == j) Console.WriteLine("this won"t execute"); 
    if(i >= j) Console.WriteLine("this won"t execute"); 
    if(i > j) Console.WriteLine("this won"t execute"); 
 
    b1 = true; 
    b2 = false; 
    if(b1 & b2) Console.WriteLine("this won"t execute"); 
    if(!(b1 & b2)) Console.WriteLine("!(b1 & b2) is true"); 
    if(b1 | b2) Console.WriteLine("b1 | b2 is true"); 
    if(b1 ^ b2) Console.WriteLine("b1 ^ b2 is true"); 
  }    
}


Demonstrate the short-circuit operators

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate the short-circuit operators. 
 
using System; 
 
public class SCops {    
  public static void Main() {    
    int n, d; 
 
    n = 10; 
    d = 2; 
    if(d != 0 && (n % d) == 0) 
      Console.WriteLine(d + " is a factor of " + n); 
 
    d = 0; // now, set d to zero 
 
    // Since d is zero, the second operand is not evaluated. 
    if(d != 0 && (n % d) == 0) 
      Console.WriteLine(d + " is a factor of " + n);  
     
    /* Now, try the same thing without short-circuit operator. 
       This will cause a divide-by-zero error.  */ 
    if(d != 0 & (n % d) == 0) 
      Console.WriteLine(d + " is a factor of " + n); 
  }    
}


Illustrates the use of the arithmetic operators

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_2.csc illustrates the use of
  the arithmetic operators
*/
public class Example3_2
{
  public static void Main()
  {
    // integers and arithmetic operators
    System.Console.WriteLine("10 / 3 = " + 10 / 3);
    System.Console.WriteLine("10 % 3 = " + 10 % 3);
    int intValue1 = 10;
    int intValue2 = 3;
    System.Console.WriteLine("intValue1 / intValue2 = " +
      intValue1 / intValue2);
    System.Console.WriteLine("intValue1 % intValue2 = " +
      intValue1 % intValue2);
    // floats and arithmetic operators
    System.Console.WriteLine("10f / 3f = " + 10f / 3f);
    float floatValue1 = 10f;
    float floatValue2 = 3f;
    System.Console.WriteLine("floatValue1 / floatValue2 = " +
      floatValue1 / floatValue2);
    // doubles and arithmetic operators
    System.Console.WriteLine("10d / 3d = " + 10d / 3d);
    System.Console.WriteLine("10.0 / 3.0 = " + 10.0 / 3.0);
    double doubleValue1 = 10;
    double doubleValue2 = 3;
    System.Console.WriteLine("doubleValue1 / doubleValue2 = " +
      doubleValue1 / doubleValue2);
    // decimals and arithmetic operators
    System.Console.WriteLine("10m / 3m = " + 10m / 3m);
    decimal decimalValue1 = 10;
    decimal decimalValue2 = 3;
    System.Console.WriteLine("decimalValue1 / decimalValue2 = " +
      decimalValue1 / decimalValue2);
    // multiple arithmetic operators
    System.Console.WriteLine("3 * 4 / 2 = " + 3 * 4 / 2);
  }
}


Illustrates the use of the bitwise operators

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_6.cs illustrates the use of
  the bitwise operators
*/
public class Example3_6
{
  public static void Main()
  {
    byte byte1 = 0x9a;  // binary 10011010, decimal 154
    byte byte2 = 0xdb;  // binary 11011011, decimal 219
    byte result;
    System.Console.WriteLine("byte1 = " + byte1);
    System.Console.WriteLine("byte2 = " + byte2);
    // bitwise AND
    result = (byte) (byte1 & byte2);
    System.Console.WriteLine("byte1 & byte2 = " + result);
    // bitwise OR
    result = (byte) (byte1 | byte2);
    System.Console.WriteLine("byte1 | byte2 = " + result);
    // bitwise exclusive OR
    result = (byte) (byte1 ^ byte2);
    System.Console.WriteLine("byte1 ^ byte2 = " + result);
    // bitwise NOT
    result = (byte) ~byte1;
    System.Console.WriteLine("~byte1 = " + result);
 
    // left shift
    result = (byte) (byte1 << 1);
    System.Console.WriteLine("byte1 << 1 = " + result);
    // right shift
    result = (byte) (byte1 >> 1);
    System.Console.WriteLine("byte1 >> 1 = " + result);
  }
}


Illustrates the use of the Boolean logical operators

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_4.cs illustrates the use of
  the Boolean logical operators
*/
public class Example3_4
{
  public static void Main()
  {
    bool result;
    // use of the Boolean logical AND operator
    result = (1 == 1) && (2 > 1);
    System.Console.WriteLine("(1 == 1) && (2 > 1) is " + result);
    result = (1 == 1) && (2 < 1);
    System.Console.WriteLine("(1 == 1) && (2 < 1) is " + result);
    // use of the Boolean logical OR operator
    result = (1 == 1) || (1 == 0);
    System.Console.WriteLine("(1 == 1) || (1 == 0) is " + result);
    result = (1 == 0) || (1 == 0);
    System.Console.WriteLine("(1 == 0) || (1 == 0) is " + result);
    // use of the Boolean logical NOT operator
    result = !(1 == 0);
    System.Console.WriteLine("!(1 == 0) is " + result);
    result = !(1 == 1);
    System.Console.WriteLine("!(1 == 1) is " + result);
  }
}


Illustrates the use of the comparison operators

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_3.cs illustrates the use of
  the comparison operators
*/
public class Example3_3
{
  public static void Main()
  {
    bool result;
    // false expressions
    result = 10 == 1;
    System.Console.WriteLine("10 == 1 is " + result);
    result = 10 < 1;
    System.Console.WriteLine("10 < 1 is " + result);
    result = 10 <= 1;
    System.Console.WriteLine("10 <= 1 is " + result);
    // true expressions
    result = 10 != 1;
    System.Console.WriteLine("10 != 1 is " + result);
    result = 10 > 1;
    System.Console.WriteLine("10 > 1 is " + result);
    result = 10 >= 1;
    System.Console.WriteLine("10 >= 1 is " + result);
    int intValue1 = 10;
    int intValue2 = 1;
    result = intValue1 != intValue2;
    System.Console.WriteLine("intValue1 != intValue2 is " + result);
  }
}


Illustrates the use of the shortcut operators

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_7.cs illustrates the use of
  the shortcut operators
*/
public class Example3_7
{
  public static void Main()
  {
    int length = 1;
    length += 10;
    System.Console.WriteLine("length = " + length);
    length *= 2;  // multiplies length by 2
    System.Console.WriteLine("length = " + length);
    length /= 3;  // divides length by 3
    System.Console.WriteLine("length = " + length);
  }
}


Illustrates the use of the ternary operator

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_5.cs illustrates the use of
  the ternary operator
*/
public class Example3_5
{
  public static void Main()
  {
    int result;
    result = 10 > 1 ? 20 : 10;
    System.Console.WriteLine("result = " + result);
    result = 10 < 1 ? 20 : 10;
    System.Console.WriteLine("result = " + result);
  }
}


Math Operators with int value

 
using System;
class Operators {
    static void Main() {
        int a, b, c, d, e;
        a = 14;
        b = 15;
        c = 20;
        d = a + b - c; //d=9
        c += d;     //c=29
        e = c + d;   //e=38
        e /= 2;     //e=19
        Console.WriteLine("{0}", e);
    }
}


Numeric Operators 1

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
namespace Client.Chapter_2___Operators_and_Excpressions
{
  public class NumericOperators1
  {
    static void Main(string[] args)
    {
      int a, b, c, d, e;
      a = 1;
      a += 1;
      b = a;
      b -= 2;
      c = b;
      c *= 3;
      d = 4;
      d /= 2;
      e = 23;
      e %= 3;
    }
  }
}


Numeric Operators 3

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
namespace Client.Chapter_2___Operators_and_Excpressions
{
  public class NumericOperators2
  {
    static void Main(string[] args)
    {
      int   a,b,c,d,e,f;
      a = 1;      //1
      b = a + 1;    //2
      b = b - 1;    //1
      c = 1; d = 2;  
      ++c;      //2
      --d;      //1
      e = --c;    // e = 1 c = 1
      f = c--;    // f = 1 c = 0
    }
  }
}


Operator precedence

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_10.cs illustrates operator precedence
*/
public class Example3_10
{
  public static void Main()
  {
    int myInt = 2 + 5 * 10;
    System.Console.WriteLine("2 + 5 * 10 = " + myInt);
    myInt = (2 + 5) * 10;
    System.Console.WriteLine("(2 + 5) * 10 = " + myInt);
    myInt = 2 * 20 / 5;
    System.Console.WriteLine("2 * 20 / 5 = " + myInt);
  }
}


Prefix and postfix versions of the increment and decrement operators

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example3_8.cs illustrates the use of
  prefix and postfix versions of the
  increment and decrement operators
*/
public class Example3_8
{
  public static void Main()
  {
    // postfix increment
    int length = 3;
    int newLength = length++;
    System.Console.WriteLine("Postfix increment example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);
    // prefix increment
    length = 3;
    newLength = ++length;
    System.Console.WriteLine("Prefix increment example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);
    // postfix decrement
    length = 3;
    newLength = length--;
    System.Console.WriteLine("Postfix decrement example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);
    // prefix decrement
    length = 3;
    newLength = --length;
    System.Console.WriteLine("Prefix decrement example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);
  }
}


Prevent a division by zero using the ? 1

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Prevent a division by zero using the ?. 
using System; 
 
public class NoZeroDiv { 
  public static void Main() { 
    int result; 
    int i; 
 
    for(i = -5; i < 6; i++) { 
      result = i != 0 ? 100 / i : 0; 
      if(i != 0)  
        Console.WriteLine("100 / " + i + " is " + result); 
    } 
  } 
}


Relational Operators

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
namespace Client.Chapter_2___Common_Type_System
{
  public class RelationalOperators
  {
    static void Main(string[] args)
    {
      int a, b;
      a = 1;
      b = 2;
      if (a > b)
        b = 10;
      if (b < a)
        a = 10;
      if (a >= b)
        b = 20;
      if (b <= a)
        a = 20;
      if (a == b)
        b = 5;
      if (b != a)
        b = a;
    }
  }
}


Relational Operators 3

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
namespace Client.Chapter_2___Operators_and_Excpressions
{
  public class RelationalOperators2
  {
    static void Main(string[] args)
    {
      int a = 10, b = 20, c = 30;
      if (a < 15 && b < 20)
        c = 10;
      if (a < 15 || b < 20)
        c = 15;
      if (!(a == 15))
        c = 25;
    }
  }
}


Self decrease

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 public class SelfMiValues
 {
     static void Main()
     {
         int original = 10;
         int result;
         // increment then assign
         result = --original;
         Console.WriteLine("After prefix: {0}, {1}", original,
             result);
         // assign then increment
         result = original--;
         Console.WriteLine("After postfix: {0}, {1}",
             original, result);
     }
 }


Self increment

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 public class SelfValues
 {
     static void Main()
     {
         int original = 10;
         int result;
         // increment then assign
         result = ++original;
         Console.WriteLine("After prefix: {0}, {1}", original,
             result);
         // assign then increment
         result = original++;
         Console.WriteLine("After postfix: {0}, {1}",
             original, result);
     }
 }


Side-effects can be important

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Side-effects can be important. 
 
using System; 
 
public class SideEffects {    
  public static void Main() {    
    int i; 
 
    i = 0; 
 
    /* Here, i is still incremented even though 
       the if statement fails. */ 
    if(false & (++i < 100)) 
       Console.WriteLine("this won"t be displayed"); 
    Console.WriteLine("if statement executed: " + i); // displays 1 
 
    /* In this case, i is not incremented because 
       the short-circuit operator skips the increment. */ 
    if(false && (++i < 100)) 
      Console.WriteLine("this won"t be displayed"); 
    Console.WriteLine("if statement executed: " + i); // still 1 !! 
  }    
}


Ternary operator

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 public class ThreeInputValues
 {
     static void Main()
     {
         int valueOne = 10;
         int valueTwo = 20;
         int maxValue = valueOne > valueTwo ?  valueOne : valueTwo;
         Console.WriteLine("ValueOne: {0}, valueTwo: {1}, maxValue: {2}",
             valueOne, valueTwo, maxValue);
     }
 }


The + Operator Is Left Associative

 

using System;
public class MainClass {
    public static void Main() {
        Console.WriteLine(10 + 25 + "A");   // Same as (10 + 25) + "A", that is "35A" 
        Console.WriteLine("A" + 10 + 25);   // Same as ("A" + 10) + 25, that is "A1025" 
    }
}