C#慢慢学 (一)(e文转)

C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++.
C# is provided as a part of Microsoft Visual Studio 7.0. In addition to C#, Visual Studio supports Visual Basic, Visual C++, and the scripting languages VBScript and JScript. All of these languages provide access to the Next Generation Windows Services (NWGS) platform, which includes a common execution engine and a rich class library. The .NET software development kit defines a "Common Language Subset" (CLS), a sort of lingua franca that ensures seamless interoperability between CLS-compliant languages and class libraries. For C# developers, this means that even though C# is a new language, it has complete access to the same rich class libraries that are used by seasoned tools such as Visual Basic and Visual C++. C# itself does not include a class library.
The rest of this chapter describes the essential features of the language. While later chapters describe rules and exceptions in a detail-oriented and sometimes mathematical manner, this chapter strives for clarity and brevity at the expense of completeness. The intent is to provide the reader with an introduction to the language that will facilitate the writing of early programs and the reading of later chapters.
1.1 Hello, world
The canonical “Hello, world” program can be written in C# as follows:
using System;
class Hello
{
    static void Main() {
        Console.WriteLine("Hello, world");
    }
}
The default file extension for C# programs is .cs, as in hello.cs. Such a program can be compiled with the command line directive
csc hello.cs
which produces an executable program named hello.exe. The output of the program is:
Hello, world
Close examination of this program is illuminating:
 The using System; directive references a namespace called System that is provided by the .NET runtime. This namespace contains the Console class referred to in the Main method. Namespaces provide a hierarchical means of organizing the elements of a class library. A “using” directive enables unqualified use of the members of a namespace. The “Hello, world” program uses Console.WriteLine as a shorthand for System.Console.WriteLine. What do these identifiers denote?  System is a namespace, Console is a class defined in that namespace, and WriteLine is a static method defined on that class.
 The Main function is a static member of the class Hello. Functions and variables are not supported at the global level; such elements are always contained within type declarations (e.g., class and struct declarations).
 The “Hello, world” output is produced through the use of a class library. C# does not itself provide a class library. Instead, C# uses a common class library that is also used by other languages such as Visual Basic and Visual C++.
For C and C++ developers, it is interesting to note a few things that do not appear in the “Hello, world” program.
 The program does not use either “::” or “->” operators. The “::” is not an operator in C# at all, and the “->” operator is used in only a small fraction of C# programs. C# programs use “.” as a separator in compound names such as Console.WriteLine.
 The program does not contain forward declarations. Forward declarations are never needed in C# programs, as declaration order is not significant.
 The program does not use #include to import program text. Dependencies between programs are handled symbolically rather than with program text. This system eliminates barriers between programs written in different languages. For example, the Console class could be written in C# or in some other language.

1.2 Automatic memory management
Manual memory management requires developers to manage the allocation and de-allocation of blocks of memory. Manual memory management is both time consuming and difficult. C# provides automatic memory management so that developers are freed from this burdensome task. In the vast majority of cases, this automatic memory management increases code quality and enhances developer productivity without negatively impacting either expressiveness or performance.
The example
using System;
public class Stack
{
    private Node first = null;
    public bool Empty {
        get {
            return (first == null);
        }
    }
    public object Pop() {
        if (first == null)
            throw new Exception("Can't Pop from an empty Stack.");
        else {
            object temp = first.Value;
            first = first.Next;
            return temp;
        }
    }
    public void Push(object o) {
        first = new Node(o, first);
    }
    class Node
    {
        public Node Next;
        public object Value;
        public Node(object value): this(value, null) {}
        public Node(object value, Node next) {
            Next = next;
            Value = value;
        }
    }
}
shows a Stack class implemented as a linked list of Node instances. Node instances are created in the Push method and are garbage collected when no longer needed. A Node instance becomes eligible for garbage collection when it is no longer possible for any code to access it. For instance, when an item is removed from the Stack, the associated Node instance becomes eligible for garbage collection.
The example
class Test
{
    static void Main() {
        Stack s = new Stack();
        for (int i = 0; i < 10; i++)
            s.Push(i);
        while (!s.Empty)
            Console.WriteLine(s.Pop());
    }
}
shows a test program that uses the Stack class. A Stack is created and initialized with 10 elements, and then assigned the value null. Once the variable s is assigned null, the Stack and the associated 10 Node instances become eligible for garbage collection. The garbage collector is permitted to clean up immediately, but is not required to do so.
For developers who are generally content with automatic memory management but sometimes need fine-grained control or that extra iota of performance, C# provides the ability to write “unsafe” code. Such code can deal directly with pointer types, and fix objects to temporarily prevent the garbage collector from moving them. This “unsafe” code feature is in fact “safe” feature from the perspective of both developers and users. Unsafe code must be clearly marked in the code with the modifier unsafe, so developers can't possibly use unsafe features accidentally, and the C# compiler and the execution engine work together to ensure that unsafe code cannot masquerade as safe code.
The example
using System;
class Test
{
    unsafe static void WriteLocations(byte[] arr) {
        fixed (byte *p_arr = arr) {
            byte *p_elem = p_arr;
            for (int i = 0; i < arr.Length; i++) {
                byte value = *p_elem;
                string addr = int.Format((int) p_elem, "X");
                Console.WriteLine("arr[{0}] at 0x{1} is {2}", i,  addr, value);
                p_elem++;
            }
        }
    }
    static void Main() {
        byte[] arr = new byte[] {1, 2, 3, 4, 5};
        WriteLocations(arr);
    }
}
shows an unsafe method named WriteLocations that fixes an array instance and uses pointer manipulation to iterate over the elements and write out the index, value, and location of each. One possible output of the program is:
arr[0] at 0x8E0360 is 1
arr[1] at 0x8E0361 is 2
arr[2] at 0x8E0362 is 3
arr[3] at 0x8E0363 is 4
arr[4] at 0x8E0364 is 5
but of course the exact memory locations are subject to change.
1.3 Types
C# supports two major kinds of types: value types and reference types. Value types include simple types (e.g., char, int, and float), enum types, and struct types. Reference types include class types, interface types, delegate types, and array types.
Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to objects. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
The example
using System;
class Class1
{
    public int Value = 0;
}
class Test
{
    static void Main() {
        int val1 = 0;
        int val2 = val1;
        val2 = 123;
        Class1 ref1 = new Class1();
        Class1 ref2 = ref1;
        ref2.Value = 123;
        Console.WriteLine("Values: {0}, {1}", val1, val2);
        Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value);
    }
}
shows this difference. The output of the program is
Values: 0, 123
Refs: 123, 123
The assignment to the local variable val1 does not impact the local variable val2 because both local variables are of a value type (int) and each local variable of a value type has its own storage. In contrast, the assignment ref2.Value = 123; affects the object that both ref1 and ref2 reference.
Developers can define new value types through enum and struct declarations, and can define new reference types via class, interface, and delegate declarations. The example
using System;
public enum Color
{
    Red, Blue, Green
}
public struct Point
{
    public int x, y;
}
public interface IBase
{
    void F();
}
public interface IDerived: IBase
{
    void G();
}
public class A
{
    protected void H() {
        Console.WriteLine("A.H");
    }
}
public class B: A, IDerived
{
    public void F() {
        Console.WriteLine("B.F, implementation of IDerived.F");
    }
    public void G() {
        Console.WriteLine("B.G, implementation of IDerived.G");
    }
}
public delegate void EmptyDelegate();
shows an example or two for each kind of type declaration. Later sections describe type declarations in greater detail.

时间: 2024-09-14 06:10:05

C#慢慢学 (一)(e文转)的相关文章

C#慢慢学 (二)(e文转)

1.14 PropertiesA property is a named attribute associated with an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural exten

好吧,就算没有什么很出色的,但可是我慢慢学过来的

书中的内容很硬啊. 慢慢理解了很多电商的编码及构架原因. 自我欣赏.

慢慢学-初学者关于指针的一个问题

问题描述 初学者关于指针的一个问题 void union(Linklist& la,Linklist&lb,Linklist&lc){ pa = la ->next;pb = lb->next; lc=pc=la; lc->next = NULL; ....... } 其中lc=pc=la; lc->next = NULL;怎么理解,la的值赋给lc就是指针lc指向头结点la,那lc 的指针域是空怎么理解呢? 解决方案 lc 有自己的内存空间,lc=la;l

阿里巴巴做手游 还要慢慢学

阿里巴巴本周宣布全平台投入手机游戏,并且拿出70%的利润与开发者共同分成,各种分析一致认为这是马云在抄马化腾的后路.事实上,拨开市场各种分析.猜测,游戏开发者又是如何看待阿里做手游这件事情?我们通过走访发现,很多游戏开发者对阿里做手游平台这事不怎么关注,有的则直说阿里不会改变现有手游格局,初期只能吸引小CP(注:指手机游戏开发者)入驻,知名的开发商还是以观望为主.有人说在中国互联网混,BAT是万万不能得罪的,其实从今年的发展速度来看,这个规律已经延续到了游戏圈,现在百度手里有91,腾讯手里有QQ

java入门的困惑,到底怎么学些java?

问题描述 以前一直觉得java开发比起c,c++,有一点low.这两年u随着大数据的兴起,感觉java越来越吃香,Apache大数据生态圈,很多开元项目都是java写的.出于工作需要,不得不接触到java,longlongago,有一点c++编程经验,但是学起java感觉很吃力.基础的一些democode倒是很容易看懂,一接触到大量代码,一个文件中各种类,一个类中又套着N多类,看着看着就晕了.平时工作很忙,也没有时间从头扎扎实实的学起,感觉达到看源码的水平,很难啊..请教各位同学,java到底要

90后站长:建站50天 让我学到的

中介交易 http://www.aliyun.com/zixun/aggregation/6858.html">SEO诊断 淘宝客 云主机 技术大厅 今天看统计的时候无意中看到统计时间已经是50天了,时间过的真快,马上就两个月了.可是看看自己的小站,每天十几的ip,真是惭愧.但是好好想想,和50天之前相比,呵呵,也算是有点收获吧!做站前和做站后的想法是完全不同的.下面谈谈个人从接触网络到建站50天的一些经历吧!(没有什么价值,纯粹是个人经历). 接触网络是在上初中那会,大概03 04年吧!

虽败犹荣的软文

这是本人写的一篇比较失败软文,发在站长论坛上,竟然有斑竹给我加了分,浏览人数也超出我的意料,对正学写软文的菜鸟我来说,是一个大大的鼓励,因此很开心地拿来和大家分享. 站长最好的学习方式是泡论坛 做站有一年多了,感觉最让我受益的还是泡论坛,从一开始我是因为泡论坛而走进网赚,逐渐成为一名站长的,到现在,我最重要的学习方式还是泡论坛. 最开始接触网站,是做调查.开始是的时候是在论坛潜水,到处找资料,什么都觉得好奇,进去看一下.开始做网赚了就到处发贴,呵呵.也开始有了几十个下线. 当时还是对网赚只知皮毛

如何让一篇软文增加最多的外链

通过写软文来提高网站权重和排名是目前青岛seo最常用的一种seo手段,相信很多站长或Seoer也都感受到了软文的力量和强大吧.曾经青岛seo专门写过一篇文章"软文在seo中的重要作用",大家可以先了解一下. 我们站长写软文,不同于那种构思巧妙的商家广告软文,不是为做某个产品而直接写软文,主要目的是给网站增加高质量的外链,通过强大的外链提升网站的权重和排名.关于软文怎么写这里暂不做深入探讨,软文主要考验的是站长写作能力的基本功,其实站长写软文相对还是很容易的,写点建站经验,写点seo技巧

新手怎样开始学平面设计?

看到很多朋友想学平面设计,但是不知道从何学起,摸不着头脑,找不到入门之处.我们现在就来谈谈进入平面设计的"大门"在哪里. 第一,了解什么是平面设计 什么是平面设计?就是用一些特殊的操作来处理一些已经数字化的图像的过程,是集电脑技术.数字技术和艺术创意于一体的综合内容.通俗地说,平面设计就是运用美术的表现形式,通过专业的电脑软件(如Photoshop Illustratour)来完成特定内容的艺术创意的行为,如设计标志,设计名片,设计海报等等.但如果这些没有通过印刷技术就无法应用出去,象