首页 > 开发 > 综合 > 正文

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

2024-07-21 02:22:21
字体:
来源:转载
供稿:网友
注册会员,创建你的web开发资料库,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.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表