Creation of C # types

Source: Internet
Author: User

Class

Class is the most common type of reference, and the simplest declarations are as follows;

Class Yournameclass

{

}

More complex classes can have the following options;

Placed before the keyword class: attribute (attributes) and class modifier (class modifiers). Non-nested class modifiers are public, internal, abstract, sealed, static, unsafe, and partial

Following yournameclass: generic type parameter (generic type parameters), one base class (base class) and one or more interfaces (interface)

Inside of parentheses: type member (class members) (including methods, properties, indexes, events, fields, constructors, operator functions, nested types, and terminators)

Field

A field is a member variable of a class (class) or struct (struct). such as: class{string name;public int=10;}

Modifiers that can be used for a field are: Static modifier: statics, access modifier: public,private,protected,internal, inheritance modifier: New

Unsafe code modifier: unsafe, read-only modifier: Readonly, thread modifier: volatile;

The read-only modifier prevents the field from being modified after the constructor function. A read-only field is assigned only in the declaration or constructor within the type.

such as: class n{readonly static int M=12;public N () {M=13}}//compile error; Cannot assign a value to a system static variable.

Field initialization is optional. A field that has not been initialized has a default value (0,%, NULL, false). The initialization of a field occurs before the constructor call;

Declare multiple fields (the same type) at the same time. Fields are separated by commas. This is a convenient way to share modifier fields with the same properties.

such as: static readonly int legs=8,eyes=1;

Method

method to perform an action through a series of statements. Method takes the parameters specified by the caller as input data. and returns the specified return value type back to the caller as the output data. Specifies a method that returns a type of void. Indicates that no value will be returned to his caller. Method can also be returned to the caller using the Ref/out parameter as output data.

In a type, the signature of a method must be unique. The signature of a method consists of the name of the method and the type of the parameter (not the parameter name, nor the return type (referred to as void. or other type))

Modifier for method:

static modifier: statics

Access modifier: Public internal private protected

Inheritance modifier: New virtual abstract override sealed

Unsafe code modifier: unsafe extern

Overloaded methods:

A method can be overloaded within a type (multiple methods have the same name), as long as his signature is not the same,

such as: void foo (int x)

void foo (double x);

void foo (int x,float y);

void foo (float x,int y);

Some are however unable to coexist, are compared:

void foo (int x);

float foo (int x);//compile error;

void goo (int [] x);

void Goo (params int[] y);//compile error;

Review the definition of signature: name and parameter type. A parameter is a parameter type (int x) that refers to the name (foo) bracket.

Passing by value and by reference

void foo (int); void foo (ref int y);//so far compile ok, void foo (out int c);//compile error;

Instance constructors

In a type or struct, the constructor runs the initialization code, and the constructor is defined as the normal function, except that his name and return value type are simplified to conform to the containing type:

public class panda{

String name;

public Panda (string n) {

Name=n;
}

Constructors can use modifiers:

Access modifier: Public internal private protected

unmanaged code modifier: unsafe extern

Since the method can be overloaded, the constructor is a special method and can be overloaded;

Overloaded constructors:

Using System;

public class wine{

public decimal price;

public int year;

Public Wine (decimal price) {price=price;}

Public Wine (decimal price,int year): this (price) {year=year;}

When a constructor calls another constructor, it is called to execute first. Invocation form: As an example.

The expression itself cannot refer to this reference, for example. He can invoke a static method to invoke an instance.


}
}

Implicitly-parameterless constructors:

For a class, the C # compiler automatically produces an parameterless constructor when and only if no function is defined, and the parameterless constructor does not occur if at least one constructor is defined.

Initialization order of constructors and fields:

The initialization of a field occurs before the constructor. and the order of initialization is the same as the order of declarations.

Non-public constructors:

Constructors are not necessarily public. A non-public constructor is typically required because a static method is called to control the creation of an instance, which is typically used to return an object from the pool instead of producing a new object, sometimes to return different types of objects based on different input parameters, such as:

public class class1{

Class1 () {}

public static Class1 Create ()

{

Perform custom logic here to return an instance of Class1;
}

}

Object initialization:

This reference:

The This reference points to the instance itself. This reference can also eliminate ambiguity.

Class pander{

String name;

public pander mate;

public void Marry (pander p) {

Mate=p;

P.mate=this;

}

}

public class test{string Name;public test (string name) {This.name=name;}}

This reference is only valid in a non-static member of a class or struct.

Properties (Attributes)

There are not many declarations and fields for attributes, just get{} and set{}.

such as: Class test{decimal f;public decimal currentprice{get{return F;} Set{f=value;}}

Modifiers for decorated properties:

static modifier: statics

Access modifier: Public internal private protected

Inheritance modifier: New virtual abstract override sealed

Unsafe code: unsafe extern

Read-only properties and computed properties:

Abstract classes and interfaces used in software development are very frequent, so the combination of some of the information on the hands of the following summary:

1. Abstract class

Abstract classes are special classes that have the following characteristics:

An abstract method makes a declaration that does not contain a concrete implementation, and can be seen as a virtual method without rewriting.

Abstract classes cannot be instantiated. Have the same attributes as other classes.

Abstract classes can have no abstract methods and abstract properties, but once you have an abstract method, you must declare the class as an abstract class.

The specific derived class must override the abstract method of the base class.

Abstract classes can be derived from another abstract class, which can override the base class's abstract methods or not, and if overridden, other derived classes must also overwrite them.

2. Interface (interface)

An interface is a reference type, similar to an abstract class but different from an abstract class.

. cannot be instantiated.

. Only the method declaration of the implementation can be included.

. Members can include methods, properties, indexers, and events.

The. interface cannot contain constants, fields (domains), constructors, destructors, or static members.

All members in an interface are implicitly considered public, so the interface cannot have a private modifier.

The. Derived class must implement all members of the interface.

A class can implement multiple interfaces directly, separated by commas.

. An interface can have multiple parent interfaces, and the class that implements the interface must implement all the members of all interfaces.

3. The difference between abstract classes and interfaces

. All can be inherited.

. Neither can be instantiated.

. Both can contain method declarations.

The. Derived class must implement a method that is not implemented.

4. The difference between abstraction and interface

The abstract class is an incomplete class that needs further refinement, and the interface is just a specification or rule of behavior, and Microsoft's custom interface always takes the able field, proving it is a "I can do ..." statement.

Abstract classes can define fields, properties, and method implementations. Interfaces can only define properties, indexers, events, and method declarations, and cannot contain fields.

Abstract classes are more defined in a series of tightly related classes, whereas interfaces are mostly defined in classes that have a loose relationship but implement a function.

The interface basically does not have any specific characteristics of inheritance, he only promises to be able to invoke the method.

. Interfaces can be implemented in multiple implementations, and abstract classes can only be inherited by a single inheritance. That is, a class may implement multiple interfaces at a time, but only with one parent class.

The. Interface can be used to support callbacks, and inheritance does not have this feature.

. Abstract classes cannot be sealed.

The concrete methods implemented by the abstract class are virtual by default, but the interface methods in the class that implement the interface are either non-virtual or virtual.

Interfaces are similar to non-abstract classes. An abstract class must also provide his own implementation for all members of the interfaces listed in the base class list of the class. However, an abstract class is allowed to map an interface method to an abstract method.

If an abstract class implements an interface, you can map the methods in the interface to an abstract class as an abstract method without having to implement the methods in the interface in the subclass of the abstract class.

5. Use of abstract classes and interfaces

Abstract classes are primarily used for closely related objects, whereas interfaces are used to provide common functionality for unrelated classes.

Use abstract classes If you want to design large functional units, or use abstract classes if you want to provide common implemented functionality across all implementations of a component.

If you create a feature that will be used across a wide range of heterogeneous objects, use an interface. Abstract classes are used if you want to design a functional block that is laugh and concise.

If you expect to create multiple versions of a component, create an abstract class. Abstract classes provide an easy way to control the component version.

. A good interface definition should be functional, not multifunctional, which would otherwise pollute the interface. If a class just implements a function in this interface, but not to implement other methods in the interface, then it is called interface pollution.

Try to avoid using inheritance to implement the build function, but instead use the black box reuse, which is the object combination. Because the hierarchy of inheritance increases, the most immediate consequence is that when you call a class in this class, you have to load all of them into the stack! The consequences can be imagined. At the same time, notice that Microsoft is building a class A lot of the time is the combination of objects. For example, the page class in ASP. Server,request properties, but they are all objects of a class. Using the page class's object to invoke the methods and properties of another class is a very basic design principle.

Abstract class reprint http://www.cnblogs.com/zhangzhongxi/archive/2011/04/25/2028501.html;

Abstract class Abstraction

   the abstract class in C # cannot be instantiated, he only provides an inherited interface for other classes

Using System;
Abstract class Myabs
{
public void Nonabmethod ()
{
Console.WriteLine ("Non-abstract Method");
}
}

Class Myclass:myabs
{
}

Class MyClient
{
public static void Main ()
{
myabs MB = new Myabs ();//cannot be instantiated

MyClass mc = new MyClass ();
Mc. Nonabmethod ();
}
}

an abstract class can contain an abstract method or an instantiated method, but an inherited class (non-abstract) must implement the abstract method
Using System;

Abstract class Myabs
{
public void Nonabmethod ()
{
Console.WriteLine ("Non-abstract Method");
}
public abstract void Abmethod (); Abstract methods, only declarations, not implemented
}

Class myclass:myabs//must implement abstract methods
{
public override void Abmethod ()
{
Console.WriteLine ("Abstarct Method");
}
}

Class MyClient
{
public static void Main ()
{
MyClass mc = new MyClass ();
Mc. Nonabmethod ();
Mc. Abmethod ();
}
}

of course, inheriting classes can also be abstract.

Using System;

Abstract class Myabs
{
public abstract void AbMethod1 ();
public abstract void AbMethod2 ();
}

//Abstract inheriting classes do not have to implement all abstract methods, and some implementations can

Abstract class Myclass1:myabs
{
public override void AbMethod1 ()
{
Console.WriteLine ("Abstarct method #1");
}
}

Class Myclass:myclass1
{
public override void AbMethod2 ()
{
Console.WriteLine ("Abstarct method #2");
}
}

Class MyClient
{
public static void Main ()
{
MyClass mc = new MyClass ();
Mc. AbMethod1 ();
Mc. ABMETHOD2 ();
}
}

abstract classes can inherit from non-abstract classes

Using System;

Class MyClass1
{
public void Method1 ()
{
Console.WriteLine ("Method of a Non-abstract class");
}
}

Abstract class Myabs:myclass1
{
public abstract void AbMethod1 ();
}

Class myclass:myabs//instance classes must implement abstract methods
{
public override void AbMethod1 ()
{
Console.WriteLine ("Abstarct Method #1 of MyClass");
}
}


Class MyClient
{
public static void Main ()
{
MyClass mc = new MyClass ();
Mc. Method1 ();
Mc. AbMethod1 ();

}
}

Abstract classes can implement interfaces

Using System;

Interface IInterface
{
void Method1 ();
}

Abstract class Myabs:iinterface
{
public void Method1 ()
{
Console.WriteLine ("Method implemented from the IInterface");
}
}

Class Myclass:myabs
{

}


Class MyClient
{
public static void Main ()
{
MyClass mc = new MyClass ();
Mc. Method1 ();
}
}

Finally, it is important to note that abstract classes cannot be declared as sealed, and these two semantics are conflicting. Abstract methods do not have to (and cannot) be declared as virtual, because they are implicitly implied as virtual!  

Transferred from: http://www.cnblogs.com/zzy2740/archive/2005/09/20/240808.html

New is more than virtual

The following chestnut:

public class BaseClass

{

public virtual void Foo () {}
}

public class Override:baseclass

{

public override void Foo () {}
}

public class New:baseclass

{

Public new void Foo () {}
}

Consider the difference between the overwrite (override) and the shield (new).

Override Override=new override ();

BaseClass Bl=overrider;

Override. Foo ();//compile Overrider. Foo;

Bl. Foo ();//compile Overrider. Foo;

///********************************////

New New1=new new ();

BaseClass Bl=new1;

New1. Foo ();//compile New1. Foo;

Bl. Foo ();//compile B1. Foo;

Surely you have made a distinction,

Cond

Creation of C # types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.