In the public account of [DotNet Development Job Hunting], the account owner prepared a batch of. NET practical interview questions for everyone:
The webmaster of this article added some detailed answers through AI. These interview questions cover all aspects of. NET development, including. NET framework, C#language, ASP.NET, ADO.NET, databases, etc. Through comparative learning, we can better understand and master these knowledge points.
During the interview process, it is very important to master and understand these interview questions. Interviewers often use these questions to assess our understanding and practical experience of. NET development. Therefore, by learning these interview questions, we can better prepare for interviews and improve our competitiveness.
-
- Interview Question Catalog: **
- What are CTS, CLS and CLR
- Comparison between CLR technology and COM technology
- How does JIT work
- How to put assemblies into GAC
- The difference between value types and reference types
- What is the difference between string and String in C#
- Briefly describe the characteristics and differences between stack and heap in. NET
- Running Mechanism of GC in. NET
- Brief introduction of the concepts of rewriting, overloading, and hiding in C#
- How to declare in C#that a class cannot be inherited
- Is Int [] reference type or value type
- Explain the basics of generics
- What is the function of Serializable?
- How to customize the serialization and deserialization process
- How to use the IFormable interface to format output
- What timer types are provided by. NET
- What are the differences and differences between the three comparison methods defined in System.Object
- Please explain the basics of delegation
- What is the difference between a delegate callback static method and an instance method
- What is a chain delegation
- Please explain the basic use of events
- Please explain the basics of reflection and the cornerstones of its implementation
- How to use reflection to implement the factory model
- How to save Type, Field, and Method information at low memory cost
- What is a thread
- How to use. NET thread pools
- What is the role of the lock keyword in C#
- Please explain how ASP.NET works
- What is the difference between GET requests and POST requests
- Introducing the page life cycle of ASP.NET
- List several methods to achieve page jumps
- How to prevent SQL injection attacks
- What data sources does ADO.NET support
- Please briefly describe the mechanism of database connection pooling
- What attributes can a connection string contain
- What is a strongly typed DataSet
- what XML is
- How to use namespaces in XML
- How to verify the format of an XML document in. NET
- What is XSLT and what does XSLT do?
- How to use XSLT documents in code
- Please briefly describe the SOAP protocol
- How to create a web service in. NET
- How to generate Web Service Proxy Types
- How to improve the reuse rate of connections in a connection pool
- What two ways do ADO.NET support to access relational databases
- What are relational databases and non-relational data
- What are the several storage methods for sessions, what are the differences, and how to set them
- Please briefly describe the functions and implementation mechanism of ViewState
- What is database row transfer and column transfer?
- What is the relationship between ADO.NET and ORM
1. CTS, CLS and CLR
CTS (Common Type System) is a specification in. NET, a common language system that defines all supported data types and operations to ensure interoperability between different languages.
CLS (Common Language Specification) is a subset of CTS that defines a minimum set of rules and conventions to ensure that code written in different languages can call each other.
CLR (Common Language Runtime) is the core component of. NET. It is responsible for compiling. NET code into executable code and executing it. It provides memory management, security, exception handling and other functions.
详解:面试必备:NET 中 .CTS、CLS 和 CLR 分别作何解释?
2. Comparison between CLR technology and COM technology
CLR technology and COM technology are both technologies used for component-based development, but there are some differences. CLR is a technology for managed code that provides functions such as automatic memory management, type safety, and exception handling. It supports multi-language development. It enables code written in different languages to be executed in a unified environment.
COM is a technology for unmanaged code and provides a component-based development mechanism, but requires manual memory management and exception handling. It only supports C++ and COM-compatible language development.
COM requires manual memory management, while CLR provides automatic garbage collection mechanisms.
CLR provides strong security and code access management, while COM has weak security.
CLR is language neutral and supports multiple languages, while COM prefers to use C++.
CLR uses metadata-based assemblies, while COM uses the registry for component registration and lookup.
3. How does JIT work
JIT: Just-In-Time is an important component of the CLR and is responsible for compiling IL code (intermediate language) into local machine code. JIT compiles IL code into machine code as needed at runtime to improve execution efficiency.
This is the basic way. NET runs executables, which means that the corresponding IL code is compiled into native instructions when it needs to be run. What is passed in the JIT is IL code, and what is output is native code, so some encryption software hooks the JIT to perform IL encryption while ensuring the normal operation of the program. JIT execution is much more efficient than interpreted code.
When a. NET program starts, IL code is first interpreted and executed by the CLR. But to improve execution efficiency, the CLR compiles IL code segment by segment into native code, and then caches it for later use.
JIT compilation is a form of deferred compilation that is compiled only when a piece of IL code actually needs to be executed.
There are three JIT models:
- Pre-compilation mode (Ngen), which pre-compiles IL code into local machine code;
- JIT-Compiler mode, which compiles IL code on demand at runtime;
- Mixed Mode, which uses both precompilation and deferred compilation.
4. How to put assemblies into GAC
Putting assemblies into GAC (Global Assembly Cache) can achieve global sharing and version management of assemblies. In common understanding, it is a place to store dLs that need to be used under various. NET platforms.
可以使用 Gacutil 工具将程序集安装到 GAC 中(gacutil /i YourAssembly.dll),也可以手动将程序集复制到 GAC 目录(一般位于C:\Windows\Assembly)中。
Or use. NET code to install it, and you can uninstall it after installation.
When referencing assemblies in GAC in a program, you can use the name of the assembly directly without specifying the full path.
5. The difference between value types and reference types
Value types and reference types are two basic data types in. NET.
Value types are stored on the stack, including simple types such as integers, floating point numbers, and characters, whose values are stored directly in variables.
Reference types are stored on the heap, including complex types such as classes, interfaces, and delegates. Variables store references to objects, references are stored somewhere on the stack or heap, and actual objects are stored on the heap.
Assignment to value types copies the actual value to the new variable, while assignment to reference types copies the reference, pointing to the same object.
Value types are passed by value, reference types by reference.
Each assignment of a value type performs a field-by-field copy, and an assignment of a reference type is just a pointer transfer, which actually generates a new pointer instance.
6. What is the difference between string and String in C#
In C#, string is the C#keyword, which represents the string type in. NET;
String is an alias for the System.String class, that is, string is an alias for String, with no substantive difference.
String is an old name from the. NET Framework. It was introduced in C#1.0 and replaced by string in C#2.0. In actual use, they can be transformed into each other without substantial differences.
7. Characteristics and differences between stack and heap in. NET
In. NET, heaps and stacks are two different ways to allocate memory.
The heap is used to store objects of reference types. The garbage collector is responsible for managing the allocation and release of memory. What is allocated by using new, malloc and other memory allocation functions is on the heap.
The stack is used to store context information for variables of value types and method calls. Memory allocation and release are automatically managed by the compiler. Variables defined in the function body are usually on the stack.
The allocation speed of the heap is slow, but memory can be dynamically allocated and released. It is out of order. It is a discontinuous memory domain that the user controls and releases by himself. If the user does not release by himself, when the memory reaches a certain value, it is recycled through the garbage collector (GC).
Stack allocation speed is fast, but its size is fixed and its life cycle is short. When storing it in the stack, the storage order must be managed and the principle of first-in-last-out is maintained. It is a continuous memory domain that is automatically allocated and maintained by the system. Stack memory does not need to be managed by us and is not managed by GC. When the top element of the stack is used up, it is released immediately. The heap requires GC cleanup. When using a reference type, it is generally an operation on a pointer rather than the reference type object itself. But the value type operates on itself.
The life cycle of the stack is determined by method calls, and objects on the heap have a longer life cycle and are managed by the garbage collector.
8. Running mechanism of GC in. NET:
GC is the abbreviation of Garbage Collect **. It is part of the CLR and an important part of the core mechanism of. NET. It is a mechanism for automatically managing memory by regularly checking objects that are no longer in use and releasing the memory they occupy. The garbage collector tracks the reference relationships of objects. When an object is no longer referenced, the garbage collector marks it as garbage and reclaims the memory it occupies when appropriate. Garbage collectors have different algorithms and strategies, such as mark-clean, copy, mark-tidy, etc.
The basic working principle is to iterate through the objects in the managed heap, mark which objects are used (which are not used is so-called garbage), then move the reachable objects to a contiguous address space (also called compression), and all the rest of the unused objects are reclaimed.
9. Concepts of rewriting, overloading and hiding
In C#, override means that a derived class reimplements a virtual method of the base class.
Overloading refers to defining multiple methods with the same name but different parameter lists in the same class, and overloading them multiple times to adapt to different needs. It refers to "overriding", which means that a subclass overrides a method of the parent class. Objects of the subclass can no longer access this method in the parent class.
隐藏(new)是指子类隐藏了父类的方法,当然,通过一定的转换,可以在子类的对象中访问父类的方法,如果使用子类声明的对象,调用隐藏方法会调用子类的,如果使用父类声明对象,那么就会调用父类中的隐藏方法。【参考:C#——隐藏方法】
Overrides and overloading are both manifestations of polymorphism, while concealment is a member of a hidden base class.
详解:面试必备:C#实现多态的过程中 overload 重载 与 override 重写的区别
10. How to declare in C#that a class cannot be inherited
In C#, you can use the sealed keyword to declare that a class cannot be inherited. When a class is declared sealed, other classes cannot inherit from the class.
sealed class MySealedClass { }
11. Is int [] reference type or value type
int [] is a reference type because it is an array type, which is a reference type and is stored on the heap, while the array variable itself is stored on the stack and points to the data in the heap.
12. Explain the basics of generics
Generics are a feature in. NET that allows type parameters to be specified at compile time for type safety and code reuse. The basic principle of generics is to generate specific types of code through compile-time type checking and type inference. At run time, generic code is instantiated to specific types to improve execution efficiency.
Generics allow you to write code that works with different data types without having to write different code for each type.
When using generics, you can define a template (class, interface, method, etc.), some of which can be specified by actual use.
13. What is the function of Serializable?
The Serializable feature is used to mark that a class can be serialized, that is, an object can be converted into a byte stream for storage or transmission. The Serializable feature tells the compiler and runtime environment that instances of this class can be serialized and deserialized.
Serialization converts an object into a byte stream, and deserialization converts a byte stream into an object.
14. How to customize the serialization and deserialization process
Custom serialization and deserialization processes can be achieved by implementing the ISerializable interface. The ISerializable interface defines two methods: GetObjectData is used to serialize the object's data into a byte stream, and CustomSerializableClass is used to obtain the constructor used when deserialization.
[Serializable]
public class CustomSerializableClass : ISerializable
{
public string Name { get; set; }
public int Age { get; set; }
// 实现 ISerializable 接口的方法
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
info.AddValue("Age", Age);
}
// 构造函数用于反序列化
protected CustomSerializableClass(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");
Age = info.GetInt32("Age");
}
}
15. How to use the IFormable interface to format output
You can format output using the IFormable interface. The IFormatable interface defines a method ToString that accepts a format string and a format provider as parameters, and converts objects to strings based on the format string and format provider's requirements.
参考:IFormattable 接口 (System) | Microsoft Learn
16. What timer types are provided by. NET
NET provides several timer types, including System.Timers.Timer, System.Threading.Timer, and System.Windows.Forms.Timer.
System.Timers.Timer
This is an event-based timer located in the System.Timers namespace. It is an encapsulation of System.Threading.Timer and is more suitable for use in a multithreaded environment because the callback method is executed by default on the thread that created the timer. It supports single or periodic task scheduling.
System.Threading.Timer
This is a thread-based timer located in the System. Threading namespace. It executes callback methods at specified time intervals, allowing single or periodic task scheduling. It should be noted that the callback method is executed on another thread, so handle thread synchronization issues carefully in the callback method.
System.Windows.Forms.Timer
This is a timer in a Windows Forms application and is located in the System. Windows.Forms namespace. It is mainly used to perform periodic UI updates in Windows Forms applications, and the callback method is executed on the UI thread.
System.Diagnostics.Stopwatch
This is a high-precision timer located in the System. Diagnostics namespace. Although not a typical timer, it is used to measure the execution time of code segments and can help you with performance analysis.
System.Threading.Tasks.Task.Delay
This is not a traditional timer, but an asynchronous delay implemented through the Task. Delay method. It allows you to wait a while and perform asynchronous operations, which can be used to implement deferred tasks.
详解:C#3 种定时器使用
17. What are the differences and differences between the three comparison methods defined in System.Object
Three comparison methods are defined in System.Object, they are Equals (object), Equals (object, object), and ReferenceEquals (object, object).
All three methods are used to compare whether two objects are equal. However, the way they compare is different.
The Equals(object) method is a virtual method and can be overridden by a subclass. It compares whether the values of two objects are equal.
The Equals(object, object) method is a static method and cannot be overridden by a subclass. It compares whether references to two objects are equal.
The ReferenceEquals(object, object) method is a static method and cannot be overridden by a subclass. It compares whether references to two objects point to the same object.
18. Please explain the basics of delegation
Delegates in C#are similar to pointers to functions in C or C++. Delegate is a reference-type variable that holds a reference to a method that can be changed at run time. It is also essentially a class that defines the type of a method so that it can be passed as a parameter to another method, a practice of dynamically assigning methods to parameters.
Delegate is a reference type used to encapsulate calls to methods, allowing methods to be passed as parameters in a manner similar to function pointers. A delegate contains a reference to a method and an optional target object. When the delegate is called, the method referenced by the delegate is actually called.
The basic principle of delegation is to invoke a method through a delegate instance, which contains the reference to the method and the context information of the invocation.
19. What is the difference between a delegate callback static method and an instance method
The difference between a delegate callback static method and an instance method lies in the way it is called. When a delegate calls back a static method, you can directly use the class name to invoke the static method; when a delegate calls back an instance method, you need to create an instance object first, and then use the instance object to invoke the instance method.
//伪代码 仅供参考
// 委托回调静态方法
Action<int> myAction = MyStaticMethod;
myAction(10);
// 委托回调实例方法
MyClass myObject = new MyClass();
Action<MyClass> myAction2 = myObject.MyInstanceMethod;
myAction2(myObject);
20. What is a chain delegation
Chained delegation refers to linking multiple delegation objects together to form a delegation chain. When a chain delegate is called, each delegate object is called in turn until a delegate object returns a non-null value or all delegate objects are called. Chained delegates can be used to implement chain of event handlers, chain of asynchronous operations, and other complex tasks.
在 C# 中,可以使用 + 运算符来链接委托。例如,以下代码将两个委托链接在一起:
Action<int> myAction1 = (x) => Console.WriteLine(x);
Action<int> myAction2 = (x) => Console.WriteLine(x * x);
Action<int> myChainedAction = myAction1 + myAction2;
myChainedAction(10); // 输出:10 100
21. Please explain the incident and basic usage methods
Events are class members that allow a class to notify other classes or code when specific conditions occur.
定义事件时,需要使用 delegate 关键字声明一个委托类型,然后定义一个事件成员。
通过 += 运算符将订阅者的方法添加到事件的委托链中,当事件触发时,委托链中的方法将被调用。
22. Please explain the basics of reflection and the cornerstones of its implementation
Reflection is a mechanism in. NET for obtaining and manipulating information of types at runtime.
Reflection is an important feature of the. NET platform, allowing information such as assemblies, types, members, etc. to be obtained and manipulated at runtime.
The basic principle of reflection is to describe the structure of a type through metadata, which can be accessed by the runtime to obtain detailed information about the type.
反射的基石是元数据(metadata),它是程序集的一部分,包含有关类型、成员、方法等的描述信息。这使得程序可以在运行时了解其自身的结构和组成。
23. How to use reflection to implement the factory model
First, understand how the factory pattern is implemented. The factory pattern replaces instantiation classes. Using reflection to implement the factory pattern allows you to create instances of objects based on specific class names or conditions without explicitly specifying the instantiation of each object (new object).
using System;
// 定义接口
public interface IVehicle
{
void Move();
}
// 实现 IVehicle 接口的两个类
public class Car : IVehicle
{
public void Move()
{
Console.WriteLine("Car is moving");
}
}
public class Bike : IVehicle
{
public void Move()
{
Console.WriteLine("Bike is moving");
}
}
// 工厂类,利用反射根据类名创建对象实例
public class VehicleFactory
{
public IVehicle CreateInstance(string vehicleType)
{
Type type = Type.GetType(vehicleType); // 获取类型
if (type == null || !typeof(IVehicle).IsAssignableFrom(type))
{
throw new ArgumentException("无效车类型");
}
// 创建实例
IVehicle vehicle = (IVehicle)Activator.CreateInstance(type);
return vehicle;
}
}
//main调用
#region
// 工厂类实例
VehicleFactory factory = new VehicleFactory();
// 通过工厂类创建不同类型的实例
IVehicle car = factory.CreateInstance("Car");
IVehicle bike = factory.CreateInstance("Bike");
car.Move(); // 输出:Car is moving
bike.Move(); // 输出:Bike is moving
#endregion
24. How to save Type, Field, and Method information at low memory cost
使用轻量级的结构如 System.Reflection.Emit 中的 DynamicMethod 或 DynamicType 来保存 Type、Field 和 Method 信息,以较小的内存开销创建和操作类型。
25. What is a thread
A thread is the smallest unit of program execution and the basic unit for task scheduling by the operating system. A process can contain multiple threads, each with its own execution path and execution state. Threads can be executed concurrently, improving program execution efficiency. In. NET, the System.Threading namespace provides support for threads.
26. How to use. NET thread pools
Thread pools allow threads to be reused to improve performance and reduce thread creation and destruction overhead. You can use the ThreadPool.QueueUserWorkItem method to queue work items into the thread pool and be executed by the threads in the thread pool. You can use the ThreadPool class to use the. NET thread pool.
static void Main()
{
// 将工作项放入线程池队列
ThreadPool.QueueUserWorkItem(DoWork, "Hello ThreadPool!");
ThreadPool.QueueUserWorkItem(DoWork, "Hello ThreadPool2!");
// 主线程继续执行其他工作
Console.WriteLine("欢迎关注公众号[dotnet开发跳槽].");
// 防止控制台直接关闭
Console.ReadLine();
}
static void DoWork(object state)
{
// 从线程池中的线程执行的工作方法
string message = (string)state;
Console.WriteLine($"ThreadPool 工作: {message}");
}
27. What is the role of the lock keyword in C#
Thread safety is the focus, and the lock keyword is used to ensure safe access to shared resources in a multi-threaded environment. It protects blocks of code by acquiring mutex on objects, so that only one thread can enter the critical section until the thread releases the lock. The lock keyword ensures that only one thread can access the locked block of code at the same time, avoiding data inconsistency caused by multiple threads accessing shared resources at the same time.
28. Please explain how ASP.NET works
ASP.NET runs on a Web server and provides Web services by processing HTTP requests and generating HTTP responses. ASP.NET can run in out-of-process or in-process modes, including IIS process hosting mode and self-managed mode.
** What if it is ASP.NET Core? **
ASP.NET Core can also run on a Web server to provide Web services by processing HTTP requests and generating HTTP responses. Unlike traditional ASP.NET, ASP.NET Core is cross-platform and can run on operating systems such as Windows, Linux, and macOS.
ASP.NET Core can run in out-of-process or in-process mode. In out-of-process mode, ASP.NET Core applications run in separate processes and can communicate with the Web server via the HTTP protocol. Common Web servers include IIS, Nginx, and Apache.
In in-process mode, ASP.NET Core applications are directly embedded into the Web server process and share the same process space with the Web server. In this mode, ASP.NET Core applications can process requests more efficiently and reduce the overhead of inter-process communication.
ASP.NET Core also supports a self-managed model, which means that the application can run directly as a stand-alone console application and does not rely on any Web server. In self-managed mode, ASP.NET Core applications can use Kestrel as a built-in Web server or other third-party Web servers.
In short, ASP.NET Core can run in out-of-process or in-process mode, and supports self-managed mode. You can choose the appropriate running mode according to specific needs.
29. What is the difference between GET requests and POST requests
GET request and POST request are two common request methods in the HTTP protocol. In fact, there is not much difference. The main difference lies in the data transmission method. GET requests attach request parameters to the URL and transmit them in clear text, which is suitable for obtaining data;POST requests place request parameters in the request body, which is safer and has no length limit, and is suitable for submitting data. Parameters for GET requests have length limits, and parameters for POST requests have no length limits.
The length of query parameters for HTTP GET requests is limited, and different browsers have different limits on the length of query parameters. The following are some common browser limitations on the length of query parameters:
- Internet Explorer: The length of query parameters for Internet Explorer 9 and below is limited to 2,083 characters.
- Microsoft Edge: The length of query parameters for the Microsoft Edge browser is limited to 8,192 characters.
- Chrome: Chrome's query parameter length is limited to 8,192 characters.
- Firefox: The length of query parameters in the Firefox browser is limited to 65,536 characters.
- Safari: The length of query parameters in the Safari browser is limited to 80,000 characters.
It should be noted that these limitations refer to the length of query parameters and do not include other parts of the URL (such as protocol, domain name, path, etc.). In addition, different versions of browsers may vary, and the above limitations are for reference only. If you need to pass long query parameters, consider using a POST request or passing the parameters in the request body.
30. Introducing the page life cycle of ASP.NET
The page life cycle of ASP.NET includes multiple stages, such as page initialization, page loading, page rendering, event processing, page unloading, etc. At each stage, ASP.NET calls corresponding event handling methods, and developers can write their own code in these methods to implement specific functions.
31. List several methods to achieve page jumps
Used in traditional MVC projects, new projects generally separate read and write. Methods to realize page jumps include: Response.Redirect, Server.Transfer, Server.Execute, navigation functions using hyperlinks or button controls, window.location methods using JavaScript, etc.
32. How to prevent SQL injection attacks
Nowadays, ORM is basically used, but it generally does not appear. To prevent SQL injection attacks, you can use parameterized queries or stored procedures to perform database operations. Parametric queries pass the data entered by the user as parameters to the database, rather than directly splicing the data entered by the user into SQL statements, verifying and filtering the input data to prevent malicious injection of SQL code. Stored procedures encapsulate SQL statements in a database and pass data entered by the user through parameters.
33. What data sources does ADO.NET support
If ADO. NET continues to be developed, the data sources supported will be unlimited. ADO. NET supports multiple data sources, including SQL Server, Oracle, OLEDB, ODBC, and XML.
34. Please briefly describe the mechanism of database connection pooling
Database connection pooling is a mechanism for managing database connections. It creates a certain number of database connections when the application starts and saves these connections in the connection pool. When the application needs to connect to the database, it obtains an available connection from the connection pool, and returns the connection to the connection pool after using it instead of closing the connection. This can reduce the time cost required to open and close the connection and improve the reuse rate and performance of the connection.
35. What attributes can a connection string contain
The connection string can contain multiple attributes, such as data source, user name, password, connection timeout, etc. Common connection string properties include: Data Source, Initial Catalog, User ID, Password, Connect Timeout, etc., depending on the database and provider you are connected to.
36. What is a strongly typed DataSet
A strongly typed DataSet is a DataSet whose structure is known at design time. It was created through Visual Studio's Dataset Designer and has compile-time type checking and IntelliSense support. In a strongly typed DataSet, the types of tables and columns are explicitly specified, rather than using the generic Object type.
37. what XML is
XML (eXtensible Markup Language) is a markup language used to store and transfer data. It uses tags to describe the structure and content of data and is self-descriptive and extensible.
38. How to use namespaces in XML
Namespaces in XML are used to avoid conflicts between element and attribute names. You can use the xmlns attribute to define a namespace and use prefixes to reference elements and attributes in the namespace.
39. How to verify the format of an XML document in. NET
You can use an XML Schema Definition (XSD) file to verify an XML document, or use the XmlReader class, or the XmlDocument class to verify the format of an XML document.
The XmlReader class provides a streaming way to read and verify XML documents. You can specify verification options by setting the properties of the XmlReaderSettings class;
The XmlDocument class provides a DOM way to read and validate XML documents, and you can specify validation options by setting the properties of the XmlValidatingReader class.
40. What is XSLT and what does XSLT do?
XSLT (eXtensible Stylesheet Language Transformations) is used to transform one XML document into another XML document, HTML page, or other text format. It is an XML-based conversion language. XSLT can transform and process XML documents by defining templates and rules, and is often used to convert XML documents into HTML, PDF and other formats.
41. How to use XSLT documents in code
Use classes in the. NET Framework, such as XslCompiledTransform or XmlDocument, to load an XSLT document, and then apply the document to transform XML data, using the Transform method to convert the XML document to another format.
42. Please briefly describe the SOAP protocol
SOAP (Simple Object Access Protocol) is a communication protocol used to exchange structured information. It uses the XML format to encapsulate and transfer data, allows communication between web-based services, and supports interoperability between different environments and languages.
43. How to create a web service in. NET
You can use the ASP.NET WebService class to create a Web Service. You can define exposed methods in a Web Service class and then mark them with the WebMethod attribute so that they can be called through an HTTP request.
44. How to generate Web Service Proxy Types
You can use the wsdl.exe tool or Visual Studio's Add Service Reference feature to generate Web Service Proxy types. The wsdl.exe tool can generate proxy classes based on the WSDL document of the Web Service, while the "Add Service Reference" function can generate proxy classes based on the metadata of the Web Service. The generated proxy class can be used to invoke Web Service methods.
45. How to improve the reuse rate of connections in a connection pool?
Answer: There are several ways to improve the reuse rate of connections in the connection pool:
- Reasonably set the parameters of the connection pool: You can set parameters such as the maximum number of connections, minimum number of connections, and connection timeout time of the connection pool according to the needs of the application. Reasonable parameter settings can avoid excessive creation and destruction of connections in the connection pool and improve the reuse rate of connections.
- Use a release mechanism for connections in a connection pool: When using connections in a connection pool, it is very important to release connection resources in a timely manner. You can use the using statement or manually call the Close method of the connection to release connection resources and ensure that the connection can be returned to the connection pool in time for reuse by other requests.
- Avoid taking up connections for long periods of time: When using connections, minimize the duration of the connection. Connection resources can be released as soon as possible after database operations are completed to avoid long-term occupation of connections and improve connection availability and reuse rate.
- Use connection string to connect pool properties: You can set connection pool-related properties in the connection string, such as the maximum number of connections, connection timeout, etc. By setting these attributes reasonably, you can control the number and life cycle of connections in the connection pool and improve the reuse rate of connections.
46. What two ways do ADO. NET support to access relational databases?
Answer: ADO. NET supports accessing relational databases through two providers:
- SQLClient Provider: The SQLClient Provider is a provider in ADO. NETused to access Microsoft SQL Server databases. It provides a set of classes and methods for connecting, executing SQL statements, and processing results to easily interact with SQL Server databases.
- OLEDB Provider: The OLEDB Provider is a common data access interface that can be used to access multiple types of relational databases. It provides a set of classes and methods for connecting, executing SQL statements, and processing results, and can be adapted to different databases through adapter patterns.
47. What is a relational database? What about non-relational databases?
A relational database is a database that uses tables to organize and store data. It uses a relational model to describe relationships between data, storing and representing data through rows and columns in tables. Relational databases use Structured Query Language (SQL) for data operations and queries.
Non-relational databases are databases that do not use relational models and SQL. They use different data models and query languages to store and manipulate data. Common non-relational databases include document databases, key-value databases, column storage databases, etc. Non-relational databases are generally more suitable for storing and processing large amounts of unstructured data and are more scalable and flexible.
48. What are the several storage methods for sessions, what are the differences between them, and how to set them?
Sessions can be stored in the following ways:
- Server memory: Store Session data in server memory. This method has fast access speed, but it will consume memory resources of the server.
- Database: Store Session data in the database. This method can achieve session persistence, but it will increase the database access overhead.
- External services (such as Redis): Store Session data in an external caching service, such as Redis. This method can realize distributed storage and sharing of sessions and improve the scalability and performance of the system.
设置 Session 的存储方式可以通过配置文件或代码来实现。在 ASP.NET 中,可以通过 Web.config 文件的<sessionState>元素来配置 Session 的存储方式和其他属性。可以设置 mode 属性来指定存储方式(如 InProc、SQLServer、Redis 等),并设置相应的连接字符串或其他配置信息。也可以通过代码来设置 Session 的存储方式,如使用 SessionStateModule 的 SessionStateMode 属性来设置存储方式。
49. Please briefly describe the functions and implementation mechanism of ViewState.
ViewState is a mechanism used to save state information for page controls between postbacks on a Web page. It can save information such as property values, event states, and view states of page controls to restore the state of the page when the page is posted back.
ViewState 的实现机制是将页面控件的状态信息保存在隐藏字段中,这个隐藏字段的名称为__VIEWSTATE。在页面回发时,ASP.NET 会自动将隐藏字段的值解析并恢复页面控件的状态。
ViewState's functions include:
- Save property values of page controls: ViewState can save property values of page controls, including the text of text boxes, the selection status of checkboxes, check-items in drop-down lists, etc.
- Save the event state of the page control: ViewState can save the event state of the page control, including button click events, check box selection events, etc.
- Save the view state of the page control: ViewState can save the view state of the page control, that is, information such as the position and style of the control on the page.
It should be noted that ViewState will increase the size of the page and increase the overhead of network transmission. When using ViewState, care should be taken to control the size of ViewState to avoid excessive data transfer and page loading delays. You can control whether ViewState is enabled by setting the EnableViewState property, and the ViewStateMode property can control the mode of ViewState (such as Enabled, Disabled, Inherit, etc.).
50. What is database row transfer and column transfer?
Database row to column and column transition refer to the operation of data conversion in the database.
Database Row to Column is an operation that converts row data in a database into column data. Typically, data in a database is stored in rows, with each row representing a record and each column representing a field. But in some cases, we may need to convert row data to column data for easier data analysis and query. This can be achieved by using aggregate functions, PIVOT operations, or custom query statements.
Database Column to Row is an operation that converts column data in the database into row data. In contrast to column conversion, column conversion converts column data in the database into row data according to certain rules. This can be achieved by using UNPIVOT operations or custom query statements.
51. What is the relationship between ADO.NET and ORM
ADO. NET (ActiveX Data Objects. NET) and ORM (Object-Relational Mapping) are two technologies used to access databases, and they have a certain relationship at the level of database access.
ADO. NET is a set of classes and methods used in the. NET framework to access databases. It provides a way to interact with the database based on connections, commands, and data readers. ADO. NET provides a series of classes (such as SqlConnection, SqlCommand, SqlDataReader, etc.) and methods to connect to the database, execute SQL statements, and process results.
ORM is a technique for mapping object models and relational databases. It maps tables and records in a database to objects and properties, allowing developers to manipulate the database in an object-oriented manner. The ORM framework automates the conversion between objects and databases, simplifying the development of the data access layer.
The relationship between ADO. NET and ORM is that ADO. NET is an underlying database access technology, while ORM provides a higher level of abstraction and encapsulation based on ADO.NET. The ORM framework can use ADO. NET as the underlying database access technology to achieve object persistence and database operations by mapping the relationship between objects and databases.
Using the ORM framework can transform database operations into operations on objects, allowing developers to focus more on the implementation of business logic without paying attention to the underlying database access details. The ORM framework can provide higher development efficiency and code maintainability, and can also provide some additional functions such as caching, deferred loading, etc. However, it should be noted that the ORM framework is not suitable for all projects and scenarios. Some complex database operations still need to be implemented using the underlying functions of ADO. NET.
summary
This article lists the. NET interview questions provided by netizens and the reference answers for each question. I hope they will help you prepare for the interview. Some of the above questions are a bit old, which also reflects the company's old technology. Since the interview scenarios and question directions are different, you can answer as appropriate according to different situations. The answers are for reference only. If you want to interview easily, you also need to continuously improve your basic knowledge and understand the latest technical directions.
If you have different opinions on the interview questions in the article, you can leave a message or make a PR under the article: