Csharp/C Sharp/Language Basics/NameSpace

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

C# Namespaces and Using

using ThatConsoleClass = System.Console;
public class NamespacesUsing
{
    public static void Main()
    {
        ThatConsoleClass.WriteLine("Hello");
    }
}


Creating an alias

using System;
using MyAlias=MyNamespace.Nested.MyClass;
namespace MyNamespace {
  namespace Nested {
       namespace MyClass {
             public class Foo
             {
                  int _Value;
                  public Foo() {
                    _Value = 0;
                  }
                  public int getValue()
                  {
                    return _Value;
                  }
             }
       }
  }
}

class Test {
  public static void Main() {
      MyAlias.Foo myFoo = new MyAlias.Foo();
      Console.WriteLine("Value {0}", myFoo.getValue());
  }
}


Define an alias to represent a namespace

// 
using CmpDb = YourCompany.SecondPartNamespace.InnerNamespace.YourClass;
namespace YourCompany.SecondPartNamespace {
  namespace InnerNamespace {
    public class YourClass {
      public static void Open( string tblName ) {
         System.Console.WriteLine("{0}", tblName );
      }
    }
  }
}
public class CH1_14 {
  public static void Main() {
    CmpDb.Open("fred");
  }
}


Demonstrate a namespace

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;
// Demonstrate a namespace. 
// Declare a namespace for counters. 
namespace Counter { 
  // A simple countdown counter. 
  class CountDown { 
    int val; 
 
    public CountDown(int n) { val = n; } 
 
    public void reset(int n) { 
      val = n; 
    } 
 
    public int count() { 
      if(val > 0) return val--; 
      else return 0; 
    } 
  } 
} 
 
public class NSDemo1 { 
  public static void Main() { 
    Counter.CountDown cd1 = new Counter.CountDown(10); 
    int i; 
 
    do { 
      i = cd1.count(); 
      Console.Write(i + " "); 
    } while(i > 0); 
    Console.WriteLine(); 
 
    Counter.CountDown cd2 = new Counter.CountDown(20); 
 
    do { 
      i = cd2.count(); 
      Console.Write(i + " "); 
    } while(i > 0); 
    Console.WriteLine(); 
 
    cd2.reset(4); 
    do { 
      i = cd2.count(); 
      Console.Write(i + " "); 
    } while(i > 0); 
    Console.WriteLine(); 
  } 
}


Demonstrate a namespace 2

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate a namespace. 
using System; 
// Bring Counter into view. 
using Counter; 
 
// Declare a namespace for counters. 
namespace Counter { 
  // A simple countdown counter. 
  class CountDown { 
    int val; 
 
    public CountDown(int n) { 
      val = n; 
    } 
 
    public void reset(int n) { 
      val = n; 
    } 
 
    public int count() { 
      if(val > 0) return val--; 
      else return 0; 
    } 
  } 
} 
 
public class NSDemo3 { 
  public static void Main() { 
    // now, CountDown can be used directly. 
    CountDown cd1 = new CountDown(10); 
    int i; 
 
    do { 
      i = cd1.count(); 
      Console.Write(i + " "); 
    } while(i > 0); 
    Console.WriteLine(); 
 
    CountDown cd2 = new CountDown(20); 
 
    do { 
      i = cd2.count(); 
      Console.Write(i + " "); 
    } while(i > 0); 
    Console.WriteLine(); 
 
    cd2.reset(4); 
    do { 
      i = cd2.count(); 
      Console.Write(i + " "); 
    } while(i > 0); 
    Console.WriteLine(); 
  } 
}


Demonstrates using as a statement

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Using.cs -- Demonstrates using as a statement
//
//            Compile this program with the following command line:
//                C:>csc Using.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using Pen = System.Drawing.Pen;
using PaintHandler = System.Windows.Forms.PaintEventHandler;
namespace nsForm
{
    public class UsingForm : Form
    {
        public UsingForm ()
        {
            this.Text = "Using Statement";
            this.Paint += new PaintHandler(this.OnPaint);
        }
        static public void Main ()
        {
            Application.Run(new UsingForm());
        }
        private Color [] clr = new Color []
                       {
                            Color.Red,
                            Color.Green,
                            Color.Blue
                       };
        private void OnPaint (object obj, PaintEventArgs e)
        {
            Rectangle client = this.ClientRectangle;
            int side = (client.Right - client.Left) / 3;
            for (int x = 0; x < 3; ++x)
            {
                using (Pen pen = new Pen(clr[x], (float) 2.0))
                {
                    client = Rectangle.Inflate (client, -10, -10);
                    e.Graphics.DrawEllipse (pen, client);
                }
            }
        }
    }
}


How the using statement is used to specify namespaces

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example6_10.cs illustrates how the using
  statement is used to specify namespaces
*/
using Sybex;
using System;

public class Example6_10
{
  public static void Main()
  {
    // the Console.WriteLine() call uses the System namespace
    Console.WriteLine("Creating a Sybex.Car object");
    // create a Car object (uses the Sybex namespace)
    Car myCar = new Car();
    myCar.make = "Toyota";
    Console.WriteLine("myCar.make = " + myCar.make);
  }
}
namespace Sybex
{
  // declare the Car class
  public class Car
  {
    public string make;
  }
}


Illustrates the use of two namespaces

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example6_7.cs illustrates the use of two namespaces
*/

public class Example6_7
{
  public static void Main()
  {
    // create a Sybex.Car object
    System.Console.WriteLine("Creating a Sybex.Car object");
    Sybex.Car myCar = new Sybex.Car();
    myCar.make = "Toyota";
    System.Console.WriteLine("myCar.make = " + myCar.make);
    // create a DifferentCompany.Car object
    System.Console.WriteLine("Creating a DifferentCompany.Car object");
    DifferentCompany.Car myOtherCar = new DifferentCompany.Car();
    myOtherCar.make = "Porsche";
    System.Console.WriteLine("myOtherCar.make = " + myOtherCar.make);
  }
}
// create the Sybex namespace
namespace Sybex
{
  // declare the Car class
  public class Car
  {
    public string make;
  }
}

// create the DifferentCompany namespace
namespace DifferentCompany
{
  // declare the Car class
  public class Car
  {
    public string make;
  }
}


Namespaces are additive

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Namespaces are additive. 
 
using System; 
 
// Bring Counter into view. 
using Counter; 
 
// Here is one Counter namespace. 
namespace Counter { 
  // A simple countdown counter. 
  class CountDown { 
    int val; 
 
    public CountDown(int n) { 
      val = n; 
    } 
 
    public void reset(int n) { 
      val = n; 
    } 
 
    public int count() { 
      if(val > 0) return val--; 
      else return 0; 
    } 
  } 
} 
 
// Here is another Counter namespace. 
namespace Counter { 
  // A simple count-up counter. 
  class CountUp { 
    int val; 
    int target; 
 
    public int Target { 
      get{ 
        return target; 
      } 
    } 
 
    public CountUp(int n) { 
      target = n; 
      val = 0; 
    } 
 
    public void reset(int n) { 
      target = n; 
      val = 0; 
    } 
 
    public int count() { 
      if(val < target) return val++; 
      else return target; 
    } 
  } 
} 
 
public class NSDemo5 { 
  public static void Main() { 
    CountDown cd = new CountDown(10); 
    CountUp cu = new CountUp(8); 
    int i; 
 
    do { 
      i = cd.count(); 
      Console.Write(i + " "); 
    } while(i > 0); 
    Console.WriteLine(); 
 
    do { 
      i = cu.count(); 
      Console.Write(i + " "); 
    } while(i < cu.Target); 
 
  } 
}


Namespaces can be nested

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Namespaces can be nested. 
 
using System; 
 
namespace NS1 { 
  class ClassA { 
     public ClassA() { 
       Console.WriteLine("constructing ClassA"); 
    } 
  } 
  namespace NS2 { // a nested namespace 
    class ClassB { 
       public ClassB() { 
         Console.WriteLine("constructing ClassB"); 
      } 
    } 
  } 
} 
 
public class NestedNSDemo { 
  public static void Main() { 
    NS1.ClassA a= new NS1.ClassA(); 
 
 // NS2.ClassB b = new NS2.ClassB(); // Error!!! NS2 is not in view 
 
    NS1.NS2.ClassB b = new NS1.NS2.ClassB(); // this is right 
  } 
}


Namespaces prevent name conflicts

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Namespaces prevent name conflicts. 
  
using System;  
  
// Declare a namespace for counters.  
namespace Counter {  
  // A simple countdown counter.  
  class CountDown {  
    int val;  
  
    public CountDown(int n) { 
      val = n; 
    }  
  
    public void reset(int n) {  
      val = n;  
    }  
  
    public int count() {  
      if(val > 0) return val--;  
      else return 0;  
    }  
  }  
}  
 
// Declare another namespace.  
namespace Counter2 {  
  /* This CountDown is in the default namespace and  
     does not conflict with the one in Counter. */ 
  class CountDown { 
    public void count() { 
      Console.WriteLine("This is count() in the " + 
                        "Counter2 namespace."); 
    } 
  } 
} 
 
public class NSDemo2 {  
  public static void Main() {  
    // This is CountDown in the Counter namespace. 
    Counter.CountDown cd1 = new Counter.CountDown(10);  
 
    // This is CountDown in the default namespace. 
    Counter2.CountDown cd2 = new Counter2.CountDown(); 
 
    int i;  
  
    do {  
      i = cd1.count();  
      Console.Write(i + " ");  
    } while(i > 0);  
    Console.WriteLine();  
  
    cd2.count(); 
  }  
}


The use of namespace hierarchies (part 1)

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example6_8.cs illustrates the use of namespace
  hierarchies (part 1)
*/

public class Example6_8
{
  public static void Main()
  {
    Sybex.UserInterface.MyClass myUI = new Sybex.UserInterface.MyClass();
    Sybex.DatabaseAccess.MyClass myDB = new Sybex.DatabaseAccess.MyClass();
    // uses class in MiddleTier namespace in Example6_9
    Sybex.MiddleTier.MyClass myMT = new Sybex.MiddleTier.MyClass();
    // call the Test() methods
    myUI.Test();
    myDB.Test();
    myMT.Test();
  }
}
namespace Sybex
{
  namespace UserInterface  // nested namespace
  {
    public class MyClass
    {
      public void Test()
      {
        System.Console.WriteLine("UserInterface Test()");
      }
    }
  }
}

namespace Sybex.DatabaseAccess  // nested namespace using dot
{
  public class MyClass
  {
    public void Test()
    {
      System.Console.WriteLine("DatabaseAccess Test()");
    }
  }
}
/*
  Example6_9.cs illustrates the use of namespace
  hierarchies (part 2)
*/

namespace Sybex  // use the Sybex namespace
{
  namespace MiddleTier  // another namespace
  {
    public class MyClass {
      public void Test() {
        System.Console.WriteLine("MiddleTier Test()");
      }
    }
  }
}


Using namespace

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
using System;
namespace nsFirst
{
    public class NameSpaceDemo
    {
        static public void Main ()
        {
            nsSecond.clsClass cls = new nsSecond.clsClass ();
            for (nsNested.WeekDays x = nsNested.WeekDays.Sunday; x < nsNested.WeekDays.DaysInWeek; ++x)
                cls.ShowDay (x);
        }
    }
    namespace nsNested
    {
       public enum WeekDays
              {
                  Sunday, Monday, Tuesday, Wednesday,
                  Thursday, Friday, Saturday, DaysInWeek
              };
    }
}
namespace nsSecond
{
    class clsClass
    {
        public void ShowDay (nsFirst.nsNested.WeekDays day)
        {
            Console.WriteLine (day);
        }
    }
}


Using the alias keyword to refer to a nested namespace

// 
using CmpDb = YourCompany.SecondPartNamespace.InnerNamespace.YourClass;
namespace YourCompany.SecondPartNamespace {
  namespace InnerNamespace {
    public class YourClass {
      public static void Open( string tblName ) {
         System.Console.WriteLine("{0}", tblName );
      }
    }
  }
}
public class CH1_14 {
  public static void Main() {
    CmpDb.Open("fred");
  }
}