[Interview questions] Common basic knowledge points of C# interviews (with sample code)

foreword

Hello everyone, this is a c# interview question that I sorted out by myself, so that I can share it while studying.


1. Similarities and differences between virtual methods and abstract methods

  • Same point
    • Both abstract methods and virtual methods can be overridden by derived classes, and methods that override parent classes by derived classes must be declared with the keyword override.
  • difference
    • A virtual method must have a method name and a method implementation; an abstract method has only a method name and no method implementation;
    • The virtual method can be implemented in the derived class or not; the abstract method is a method to force the derived class to override, and the subclass must implement it, otherwise the derived class will not be instantiated;
    • Abstract methods can only be declared in abstract classes, not virtual methods. If a class contains abstract methods, then the class must also be declared as an abstract class;
    • Abstract methods are declared with the modifier abstract, and virtual methods are declared with the method modifier virtual;
using System;

public abstract class AbstProgram            // 必须声明为抽象类 
{
    
    
    public abstract string abstMethod();     // 抽象方法

    public virtual void virMethod()          // 虚方法
    {
    
    
        Console.WriteLine("hello, virmethod");
    }
}

public class Subclass: AbstProgram
{
    
    
    // 抽象方法必须实现
    public override string abstMethod()
    {
    
    
        return "hello,abstMethod"; 
    }

    // 虚方法可以实现,也可以选择不实现
    //public override void virMethod()
    //{
    
    
    //    Console.WriteLine("hello,virmethod");
    //}
}

Second, the similarities and differences between abstract classes and interfaces

  • Same point
    • can be inherited
    • cannot be instantiated directly
    • Both can contain method declarations and neither implements
    • Derived classes must implement unimplemented members
  • difference
    • Interfaces support multiple implementations, and abstract classes can only be implemented by single inheritance;
    • The member access type in the interface is public by default, and cannot be modified by other access modifiers;
    • The defined keywords are different, the abstract class needs abstract, and the interface uses interface;
    • Interfaces can act on value types (enumerations can implement interfaces) and reference types, and abstract classes can only act on reference types;
    • Interfaces cannot contain fields and implemented methods. Interfaces only contain signatures of methods, properties, indexers, and events; abstract classes can define fields, properties, and methods that contain implementations;
    • In an abstract class, if a new method is added, it does not need to be used for any processing in the inherited class; while for an interface, it is necessary to modify the inherited class and provide a newly defined method;
    • Interfaces are used for specifications, emphasizing contracts more, and abstract classes are used for commonality, emphasizing father and son. An abstract class is a high degree of aggregation of a class of things, so for a subclass inheriting an abstract class, for an abstract class, it belongs to the relationship of "Is A"; while an interface defines a behavior specification, emphasizing the relationship of "Can Do", Therefore, for the subclasses that implement the interface, compared to the interface, it is "the behavior needs to be completed according to the interface";
public interface IMyInterface       // 接口
{
    
    
    public void intMethod(); 
}

public abstract class AbstProgram       // 抽象类
{
    
    
    public abstract void abstMethod();   
}


public class SubClass: AbstProgram, IMyInterface
{
    
    
    public override void abstMethod()
    {
    
    
        Console.WriteLine("hello,abstMethod");
    }

    public void intMethod()
    {
    
    
        Console.WriteLine("hello,intMethod");
    }
}

3. Similarities and differences between interfaces and classes

  • Same point
    • Interfaces, classes, and structs can all inherit from multiple interfaces;
    • An interface is similar to an abstract base class, and any non-abstract type that inherits an interface must implement all members of the interface;
    • Both interfaces and classes can contain events, indexers, methods and properties;
  • difference
    • Interfaces cannot be instantiated directly;
    • Interfaces can implement multiple inheritance, and classes can only be inherited by derived classes alone;
    • The interface only contains the declaration of the method or property, not the implementation of the method, but the method defined by the class must be implemented;
    • The meaning of the expression is different. The interface defines the "grammatical contract" that all classes should follow when inheriting the interface; the interface defines the "what" part of the grammatical contract, and the derived class defines the "how to" part of the grammatical contract;
// 定义接口 
interface IMyInterface
{
    
    
    void MethodToImplement();           // 接口成员
}

class InterfaceImplementer: IMyInterface
{
    
    
    static void Main()
    {
    
    
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

    // 类实现接口
    public void MethodToImplement()
    {
    
    
        Console.WriteLine("MethodToImplement() called.");
    }
}

Four, the difference between virtual, sealed, override and abstract

  • The keyword virtual declares a virtual method, indicating that the method can be overridden.
  • sealed indicates that the class cannot be inherited, that is, the class is declared as a sealed class.
  • override overrides the method of the base class/parent class.
  • abstract is a keyword for declaring abstract classes and abstract methods. Abstract methods do not provide implementation and are implemented by subclasses. Abstract classes cannot be instantiated.
public abstract class Program
{
    
    
    public abstract string abstmethod();     // abstract

    public virtual void virmethod()          // virtual 
    {
    
    
        Console.WriteLine("hello,virmethod");
    }
}

public sealed class SubClass: Program      // sealed
{
    
    
    public override string abstmethod()      // override
    {
    
    
        return "hello,abstmethod";
    }
}

5. The difference between const and readonly

  • A const field can only be initialized in the field's declaration; a readonly field can be initialized in either the declaration or the constructor. Therefore, the readonly field may have different values ​​depending on the constructor used.
  • The const field is a compile-time constant, and the readonly field is a runtime constant, which is confirmed at runtime (one is determined at compile time, and the other is determined at runtime).
  • const is static by default, and if readonly is set to static, the statement must be displayed.
  • const For constants of reference type, the possible values ​​can only be string and null; and readonly can be any type.
using System; 

class Program
{
    
    
    public static readonly int NumberA = NumberB * 10;
    public static readonly int NumberB = 10;

    public const int NumberC = NumberD * 10;
    public const int NumberD = 10;

    static void Main(string[] args)
    {
    
    
        Console.WriteLine("NumberA is {0}, NumberB is {1}.", NumberA, NumberB);     //NumberA is 0, NumberB is 10.
        Console.WriteLine("NumberC is {0}, NumberD is {1}.", NumberC, NumberD);     //NumberC is 100, NumberD is 10.
        Console.ReadLine();
    }
}

6. What is the difference between overload and override

  • Overloading: Method overloading occurs when a class contains two methods with the same name but different signatures (same method name, different parameter list). Use method overloading to provide methods that accomplish the same semantically but perform different functions. (in one class, multiple methods)
  • Override: Used in class inheritance, by overriding the method of the subclass, the implementation of the virtual method of the parent class can be changed. (more than two classes)
public class Program
{
    
    
    // 重载 (overload)
    public void method(int num1)
    {
    
    
    }
    
    public void method(string str1)
    {
    
    
    }

    // 虚方法
    public virtual void virtmethod()
    {
    
    
        Console.WriteLine("hello,virtmethod");
    }
}

public class SubClass: Program
{
    
    
    // 重写 (override)
    public override void virtmethod()
    {
    
    
        Console.WriteLine("hello,overload");
    }
}

Seven, the difference between structure and class

  • Structs are value types and classes are reference types.
  • Structs are often used for data storage, and classes are mostly used for behavior.
  • Classes support inheritance, while structures do not.
  • Classes can be abstract classes, and structures do not support abstract patterns.
  • Structures do not support no-argument constructors, nor destructors, and cannot have the Protected modifier.
// Books结构体实现
struct Books
{
    
    
    public string title;
    public string author;
    public string subject;
    public int book_id;
};

Eight, the difference between ref and out

  • When using a ref type parameter, the incoming parameter must be initialized first; for out, it must be initialized in the method.
  • When using ref and out, the ref or out keyword must be added to the parameters of the method and when the method is executed to meet the matching.
  • out is suitable for use where multiple return values ​​need to be retrun, and ref is used when the called method needs to modify the caller's reference.
class Program
{
    
    
    public void test1(ref int i)
    {
    
    
        i = 99;
    }

    public void test2(out int i)
    {
    
    
        i = 11;
    }

    static void Main(string[] args)
    {
    
    
        Program p = new Program();

        int i = 1;
        p.test1(ref i);     // i = 99

        int j;
        p.test2(out j);     // j = 10
    }
}

Nine, the difference between value types and reference types

  • Value type: is an object that contains the actual data. That is, when defining a variable of value type, C# will allocate a storage area of ​​appropriate size to this variable in the form of a stack according to the type it declares, and then read or write operations on this variable directly in this memory area conduct;
  • Reference Types: Variables of a reference type do not store the actual data they represent, but instead store a reference to the actual data. The reference type is created in two steps: first create a reference variable on the stack, then create the object itself on the heap, and then assign the handle of this memory (also the first address of the memory) to the reference variable;
//引用类型(由于使用了'Class')
class SomeRef {
    
     public Int32 x; }

//值类型(由于使用了'Struct')
struct SomeVal {
    
     public Int32 x; }  

class Program
{
    
    
    static void ValueTypeDemo()
    {
    
    
        SomeRef r1 = new SomeRef();     
        SomeVal v1 = new SomeVal();     
        r1.x = 5;                       
        v1.x = 5;                       
        Console.WriteLine(r1.x);   //显示"5"
        Console.WriteLine(v1.x);   //同样显示"5"

        SomeRef r2 = r1;    
        SomeVal v2 = v1;    
        r1.x = 8;   
        v1.x = 9;   

        Console.WriteLine(r1.x);    //显示"8"
        Console.WriteLine(r2.x);    //显示"8"
        Console.WriteLine(v1.x);    //显示"9"
        Console.WriteLine(v2.x);    //显示"5"
    }
}

10. What is the definition of unboxing and boxing and the performance impact of unboxing and boxing? How to deal with it?

  • Boxing: Converting a value type to a reference type; Unboxing: Converting a reference type to a value type;
  • Impact: Both involve memory allocation and object creation, which have a large performance impact;
    solution: use generics;
public class Solution
{
    
    
    static void Main(string[] args)
    {
    
    
        int i = 123;        //声明一个int类型的变量i,并初始化为123
        object obj = i;     //执行装箱操作
        Console.WriteLine("装箱操作:值为{0},装箱之后对象为{1}", i, obj);
        int j = (int)obj;   //执行拆箱操作
        Console.WriteLine("拆箱操作:装箱对象为{0},值为{1}", obj, j);
    }
}

11. What is commission? Is the event a delegate?

  • The delegate (Delegate) in c# is similar to the pointer of the function in c or c++. A delegate is a reference type variable that holds a reference to a method. References can be changed at runtime. Delegate is especially used to implement events and callback methods. All delegates (Delegate) are derived from the System.Delegate class.
  • Events are special delegates, which are implemented internally based on delegates.
delegate int NumberChanger(int n);
class TestDelegate
{
    
    
    static int num = 10;
    public static int AddNum(int p)
    {
    
    
        num += p;
        return num;
    }

    public static int MultNum(int q)
    {
    
    
        num *= q;
        return num;
    }
    public static int GetNum()
    {
    
    
        return num;
    }

    static void Main(string[] args)
    {
    
    
        // 创建委托实例
        NumberChanger nc1 = new NumberChanger(AddNum);
        NumberChanger nc2 = new NumberChanger(MultNum);
        // 使用委托对象调用方法
        nc1(25);
        Console.WriteLine("Value of Num: {0}", GetNum());   // Value of Num: 35
        nc2(5);
        Console.WriteLine("Value of Num: {0}", GetNum());   // Value of Num: 175
        Console.ReadKey();
    }
}

12. Can the constructor Constructor be inherited? Can it be overloaded by Override?

  • Constructor cannot be inherited, so it cannot be rewritten (Overriding), but it can be overloaded (Overloading).
public class Student
{
    
    
    public int Age {
    
     get; }
    public string Name {
    
     get; }

    public Student()
    {
    
    
        Console.WriteLine("对象被创建。");
    }

    public Student(string name) : this()
    {
    
    
        this.Name = name;
    }

    public Student(string name, int age) : this(name)
    {
    
    
        this.Age = age;
    }
}

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Student student_1 = new Student();
        Student student_2 = new Student("姓名", 14);
        Console.WriteLine(student_2.Name + ' ' + student_2.Age);
    }
}

13. Can the String class be inherited?

  • The String class is a sealed class and cannot be inherited.
  • When applied to a class, the sealed modifier prevents other classes from inheriting from that class. In the example below, class SealedProgram inherits from class DemoProgram, but no class can inherit from class SealedProgram.
class DemoProgram {
    
     };
sealed class SealedProgram: DemoProgram {
    
     }; 

Fourteen, the difference between Task and Thread

  • Task is relatively new, released in .NET 4.5 version, while Thread is in .NET 1.1 version.
  • Task can write code in combination with the new async/await code model, while Thread does not support it.
  • Task can create a thread pool, return to the main thread, and manage APIs, but Thread cannot.
  • Task is multi-core and multi-threaded, and Thread is single-core and multi-threaded.
public class Solution
{
    
    
    static void Main()
    {
    
    
        var testTask = new Task(() =>
        {
    
    
            Console.WriteLine("hello, Task");
        });
        Console.WriteLine(testTask.Status);     // Created 
        testTask.Start();
    }
}
public class Solution 
{
    
    
    static void Main(string[] args)
    {
    
    
        ThreadTest test = new ThreadTest();             //创建ThreadTest类的一个实例
        Thread thread = new Thread(new ThreadStart(test.MyThread));             //调用test实例的MyThread方法
        thread.Start();             //启动线程
        Console.ReadKey();
    }
}

public class ThreadTest
{
    
    
    public void MyThread()
    {
    
    
        Console.WriteLine("这是一个实例方法");
    }
}

15. What are the necessary conditions for deadlock? how to overcome

  • The main causes of deadlock are:
    • Because of insufficient system resources.
    • The order in which the processes run advance is not appropriate.
    • Misallocation of resources, etc. If the system resources are sufficient and the resource requests of the process can be satisfied, the possibility of deadlock is very low; otherwise, it will fall into a deadlock due to competition for limited resources. Secondly, the progress sequence and speed of process running are different, and deadlock may also occur.
  • necessary conditions
    • Mutual exclusion: A resource can only be used by one process at a time.
    • Non-deprivation condition: The resources obtained by the process cannot be forcibly deprived until they are used up.
    • Circular waiting condition: A head-to-tail circular waiting resource relationship is formed among several processes.
    • Request and hold conditions: When a process is blocked due to requesting resources, it will hold on to the obtained resources.
  • Measures to deal with deadlock
    • Deadlock prevention: By setting certain restrictions to destroy one or more of the four necessary conditions for deadlock to prevent the occurrence of deadlock.
    • Avoid deadlock: In the process of dynamic allocation of resources, use some method to prevent the system from entering an unsafe state, so as to avoid the occurrence of deadlock.
    • Deadlock detection: deadlock is allowed during system operation, but a detection mechanism can be set to detect the occurrence of deadlock in time and take appropriate measures to eliminate it.
    • Deadlock removal: When a deadlock is detected, appropriate measures are taken to free the process from the deadlock state.

16. What is the difference between Error and Exception?

  • Errors are uncatchable and no recovery action can be taken. Except represents recoverable exceptions, which are catchable. For example: Going shopping with my son, if the son likes an Ultraman, it is Exception, and if he does not bring money, it is Error.
  • Error represents more system problems, such as system crash, virtual machine error, insufficient memory space, method call stack overflow, memory overflow, etc.; while the Exception class represents the exception that the program can capture (for example, the try-catch statement of c# ), which can be caught and possibly restored. When such an exception occurs, it should be dealt with in time to make the program run normally, so as to avoid affecting the operation of the entire project.

17. What is the difference between UDP and TCP connections?

  • TCP is a transmission control protocol, which provides connection-oriented, reliable, byte stream services, and TCP provides timeout redial and data inspection functions.
  • UDP is the User Datagram Protocol, which is a simple datagram-oriented transport protocol and is an unreliable connection.
  • TCP guarantees data correctness, UDP may lose packets, TCP guarantees data order, and UDP does not.
  • TCP has more requirements on system resources, and UDP has less requirements.

Eighteen, the usage of the new keyword

  • The new operator is used to create objects and call constructors.
  • The new modifier is used to hide inherited members from base class members.
  • new constraints are used in generic declarations to constrain the types of parameters that may be used as type parameters.
// where T:new()指明了创建T的实例时应该具有构造函数
class ItemFactory<T> where T : new()
{
    
    
    public T GetNewItem()
    {
    
    
        return new T();
    }
}
class Class1 
{
    
     
}; 
class Prorgam
{
    
    
    Class1 o = new Class1();  // 用于创建对象和调用构造函数
    int myInt = new int();    // 也用于为值类型调用默认的构造函数
}

Nineteen, the usage of the Using keyword

  • reference namespace;
  • Create an alias for a namespace or type; (using + alias = specific type including detailed namespace information)
  • Release the resource (close the file stream);
using System;       // 引用命名空间; 
using myClass1 = NameSpace1.MyClass;    // 为命名空间或类型创建别名;
using myClass2 = NameSpace2.MyClass; 

namespace ConsoleApp
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            myClass1 my1 = new myClass1();
            Console.WriteLine(my1);
            using (myClass2 my2 = new myClass2())   // 释放资源(关闭文件流);
            {
    
    
                Console.WriteLine(my2);
            }
        }
    }
}

namespace NameSpace1
{
    
    
    public class MyClass
    {
    
    
        public override string ToString()
        {
    
    
            return "hello, myClass1";
        }
    }
}

namespace NameSpace2
{
    
    
    public class MyClass: IDisposable
    {
    
    
        public void Dispose()
        {
    
    
            throw new NotImplementedException();
        }

        public override string ToString()
        {
    
    
            return "hello, myClass2";
        }
    }
} 

Twenty. The rules for a column of numbers are as follows: 1, 1, 2, 3, 5, 8, 13, 21, 34... Find the 30th digit, and use a recursive algorithm to achieve it.

  • C# implements the Fibonacci sequence;
class Solution
{
    
    
    static int Fib(int n)
    {
    
    
        if (n <= 0)
            return 0;
        if (n < 3)
            return 1;
        return Fib(n - 1) + Fib(n - 2);
    }

    static void Main(string[] args)
    {
    
    
        Console.WriteLine(Fib(30));
    }
}

Notice

Part of the graphic content in this chapter comes from the information provided by various websites and netizens. The author organizes and collects it for easy reference. The copyright belongs to the original author.

Guess you like

Origin blog.csdn.net/weixin_61361738/article/details/128757100