C# Getting Started 4

table of Contents

class

Define the interface

Constructor and destructor

Member of class

Define fields

Definition method

Define attributes

Advanced content of the class

Hide base class methods

Call overridden or hidden base class method

Nested type definition

Implementation of the interface

Implement the interface in the class


class

Use class keyword definition

class MyClass
{
    //Class members;
}

Use public to declare public classes, such classes can be accessed by code in other projects

public class MyClass
{
    //Class members;
}

Use abstract to declare an abstract class, the class cannot be instantiated, only inherited

public abstract class MyClass
{
    //Class members,mya be abstract;
}

Use sealed to declare a sealed class, which cannot be inherited

public sealed class MyClass
{
    //Class members;
}

Define the interface

Use interface to declare an interface

interface IMyInterface
{
    //Interface members;
}

Use public to define a public interface

public interface IMyInterface
{
    //Interface members;
}

Note

  1. In the definition of a C# class, there can only be one base class. If you inherit an abstract class, you must implement all the inherited abstract members (unless the derived class is also abstract).
  2. The compiler does not allow derived classes to have higher accessibility than base classes, that is, inner classes can inherit from a public base class, but public base classes cannot inherit from an inner base class.
  3. If there is no base class, all classes inherit System.Object by default
  4. The class can use a colon to specify the supported interface. If the base class is specified, the base class must immediately follow the colon, and then the specified interface; if the base class is not specified, the interface follows the colon. Use a comma to separate the interface and the base Class name.
  5. The class that supports this interface must implement all interface members, but if you don’t want to use a given interface member, you can provide an "empty" implementation (without function code), and you can also implement interface members as abstract members in an abstract class .
//添加接口
public class MyClass : IMyInterface
{
    //Class members;
}

//含基类
public class MyClass : MyBase , IMyInterface
{
    //Class members;
}

Constructor and destructor

class MyClass
{
    //显示创建默认构造函数
    public MyClass()
    {
        //Constructor code
    }
}

class MyClass
{
    //显示创建私有默认构造函数--不可以使用这个构造函数创建类的对象实例
    private MyClass()
    {
        //Constructor code
    }
}

class MyClass
{
    public MyClass()
    {
        //Default constructor code
    }
    
    //非默认构造函数
    public MyClass(int myInt)
    {
        //Nondefault constructor code(use myInt)
    }
}

class MyClass
{
    //析构函数,垃圾回收时执行析构函数中代码,释放资源
    ~MyClass()
    {
        //Destructor body
    }
}

Member of class

One of the following keywords is required to define the members of the class

  1. public: members can be accessed by any code
  2. private: members can only be accessed by code within the class (if no keywords are used, this keyword is used by default)
  3. internal: members can only be accessed by internal code in the assembly (project) that defines it
  4. protected: members can only be accessed by code in the class or derived classes

The latter two keywords can be used in combination. If there is a protected internal member, it means that it can only be accessed by derived code in the project.

You can also use static to declare fields, methods and properties, expressed as static members of the class rather than members of the object instance

Define fields

Use standard variable declaration format + keyword definition above

class MyClass
{
    public int myVar;
    //关键字readonly表示这个字段只能在执行构造函数时或初始化赋值语句赋值
    public readonly int myVar = 1;
    //static关键字将字段声明为静态,定义为静态后只能通过定义他们的类来访问:MyClass.myVar
    public static int myVar;
}

Definition method

Use standard function format + keywords above to define

class MyClass
{
    public <baseType> <functionName>
    //eg
    public string getString() => return "Here is a string"
}

You can also use the following keywords

virtual: method can be overridden

abstract: The method must be rewritten in a non-abstract derived class (only used in abstract classes)

override: The method overrides a base class method (if the method is overridden, this keyword must be used)

extern: the method is defined elsewhere

public class MyBaseClass
{
    public virtual void DoSomething()
    {
        //Base implementation
    }
}

public class MyDerivedClass : MyBaseClass
{
    //重写方法
    public override void DoSomething()
    {
        //Derived class implementation,overrides base implementation.
    }
}

public class MyDerivedClass : MyBaseClass
{
    //使用sealed关键字指定派生类中不能对该方法做进一步修改
    public override sealed void DoSomething()
    {
        //Derived class implementation,overrides base implementation.
    }
}

Define attributes

The basic structure of attributes: standard access modifiers (public etc.) + class name + attribute name + get/set block

public int MyIntProp
{
    //读属性
    get
    {
        //Property get code
    }
    
    //写属性
    set
    {
        //Property set code
    }
}

The get block must have a return value of the attribute type, and set uses a similar method to assign a value to the field

public int MyIntProp
{
    //读属性
    get
    {
        //Property get code
        return myInt;
    }
    
    //写属性
    set
    {
        //Property set code
        myInt = value;
    }
}

Advanced content of the class

Hide base class methods

public class MyBaseClass
{
    public void DoSomething()
    {
        //Base implementation
    }
}

public class MyDerivedClass : MyBaseClass
{
    public void DoSomething()
    {
        //Derived class implementation,hides base implementation
    }
}

public class MyDerivedClass : MyBaseClass
{
    //new可以显示表明隐藏基类方法
    new public void DoSomething()
    {
        //Derived class implementation,hides base implementation
    }
}

//注意区别重写方法和隐藏基类
public class MyBaseClass
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Base imp");
    }
}

//重写
public class MyDerivedClass : MyBaseClass
{
    public override void DoSomething()
    {
        Console.WriteLine("Derived imp");
    }
}

//隐藏
public class MyDerivedClass : MyBaseClass
{
    new public void DoSomething()
    {
        Console.WriteLine("Derived imp");
    }
}



//实例--注意区别隐藏和重写,隐藏基类方法不必是虚方法
public class MyBaseClass 
{ 
    public virtual void DoSomething() 
    { 
        Console.WriteLine("base class"); 
    } 
} 
    
//隐藏
public class MyDerivedClass : MyBaseClass 
{ 
    new public void DoSomething() { } 
} 
 
public class MyDerivedOverClass : MyBaseClass 
{ 
    public override void DoSomething() 
    { 
        Console.WriteLine("new class"); 
    } 
} 
 
class Program 
{ 
    static void Main(string[] args) 
    { 
             
        MyDerivedClass myDerivedClass = new MyDerivedClass(); 
        MyDerivedOverClass myDerivedOverClass = new MyDerivedOverClass(); 

        MyBaseClass myBaseClass = myDerivedClass; 
        
        myBaseClass.DoSomething();              //output : base class 
        myDerivedOverClass.DoSomething();      //output : new class 
        
        myBaseClass = myDerivedOverClass; 
        myBaseClass.DoSomething();              //output : new class 
    } 
}

Call overridden or hidden base class method

Use the base keyword to indicate the implementation code of the base class contained in the derived class

public class MyBaseClass
{
    public virtual void DoSomething()
    {
        //Base implementation
    }
}

public class MyDerivedClass : MyBaseClass
{
    public override void DoSomething()
    {
        //Derived class implementation,extends base class implementation
        base.DoSomething();
        //More derived class implementation;
    }
}

Note that base uses an object instance, and an error will be reported when used in a static member

this keyword

This can be used inside a class member to refer to the current object instance, and it cannot be used in a static member.

The most commonly used function of this is to pass the reference of the current object instance to a method, as follows

public void doSomething()
{
    MyClass myObj = new MyClass();
    myObj.DoSomething(this);
}

The above example indicates that there is a method DoSomething in the instantiated object myObj of MyClass, which takes a parameter. The parameter type can be a class type, a class type inherited by this class, or an interface implemented by this class or System.Object.

Another commonly used method of this is to limit the members of local types, as follows:

public class MyClass
{
    private int someData;
    public int SomeData
    {
        get
        {
            return this.someData;
        }
    }
}

Nested type definition

You can define the class in the class, as follows

public class MyClass
{
    public class MyNestedClass
    {
        public int NestedClassField;
    }
}

To instantiate MyNestedClass outside of MyClass, the name must be qualified, as follows

MyClass.MyNestedClass myObj = new MyClass.MyNestedClass();

In particular, if the nested class is declared as private, it cannot be instantiated externally as above

//嵌套类实例
public class ClassA 
{ 
    private int state = -1; 
    public int State 
    { 
        get 
        { 
            return state; 
        } 
    } 
    
    public class ClassB 
    { 
        public void SetPrivateState(ClassA target,int newState) 
        { 
            target.state = newState; 
        } 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
        ClassA myObject = new ClassA(); 
        Console.WriteLine($"myObject.State = {myObject.State}"); 
        ClassA.ClassB myOtherObject = new ClassA.ClassB(); 
        myOtherObject.SetPrivateState(myObject, 999); 
        Console.WriteLine($"myObject.State = {myObject.State}"); 
        Console.ReadKey(); 
    } 
}

Implementation of the interface

The interface is defined by the interface keyword. The members defining the interface are similar to the class members, but there are several important differences

  1. Access modifiers (public, private, protected, internal) are not allowed, and all interface members are implicitly public.
  2. Interface members cannot contain code body
  3. Interface cannot define field members
  4. The keywords static, virtual, abstract or sealed cannot be used to define interface members
  5. Type definition members are forbidden-interfaces cannot be defined as members of other interfaces

In particular, hidden members inherited from the base interface can be defined with the keyword new, as follows

interface IMyBaseInterface
{
    void DoSomething();
}

interface IMyDerivedInterface : IMyBaseInterface
{
    new void DoSomething();
}

Similarly, the attributes defined in the interface can define which of the access blocks get and set can be used for the attribute

interface IMyInterface
{
    int MyInt
    {
        get;
        set;
    }
}

Implement the interface in the class

The class that implements the interface must contain the implementation code of all members of the interface, and must match the specified signature (including matching the specified get and set blocks), and must be public, as follows:

public interface IMyinterface
{
    void DoSomething();
    void DoSomethingElse();
}

public class MyClass : IMyInterface
{
    public void DoSomething(){}
    public void DoSomethingElse(){}
}

You can use the keywords virtual or abstract to implement interface members, but you cannot use static or const. You can also implement interface members on the base class.

public interface IMyInterface
{
    void DoSomething();
    void DoSomethingElse();
}

public class MyBaseClass
{
    public void DoSomething(){}
}

public class MyDerivedClass : MyBaseClass, IMyinterface
{
    public void DoSomethingElse(){}
}

In particular, inheriting a base class that implements a given interface means that the derived class implicitly supports this interface

public interface IMyInterface
{
    void DoSomething();
    void DoSomethingElse();
}

public class MyBaseClass
{
    public virtual void DoSomething(){}
    public virtual void DoSomethingElse(){}
}

public class MyDerivedClass : MyBaseClass
{
    public override void DoSomething(){}
}

 

Guess you like

Origin blog.csdn.net/wyzworld/article/details/113114226