"New chapter of 2017". NET face Question Summary (i)

Source: Internet
Author: User

Directory

    • This is to introduce me to the collection and my own personal preservation some. NET face questions
    • Brief introduction
      • 1.c# the difference between a value type and a reference type
      • 2. How to enable a type to be used in a foreach statement
      • What are the characteristics of 3.sealed modified classes?
      • 4. Object-oriented 3 basic features
      • 5.. NET managed resources and unmanaged resources
      • 6.string str=null and string str= "" What's the difference?
      • What does 7.StringBuilder do?
      • 8. What is the role of serialization
      • Where to use 9.BASE64 encoding
      • 10. How does a string pool improve system performance?
      • 11.FileInfo and DirectoryInfo
      • 12.datetime.parse (mystring) What's wrong with this line of code?
      • Similarities and differences of three comparative methods of 13.system.object
      • How does the 14.GetHashCode approach work? When will this method be used?
      • 15. Principle of Delegation
      • 16. What is the difference between a delegate callback static method and an instance method
      • 17. What is a chained delegate?
      • 18.asp.net operating mechanism
      • What is the use of static variables and methods in 19.c#

Body

Back to the top this time to introduce to you is my collection and personal preservation some. NET face questions back to top introduction
    • This includes more than just. net knowledge , also contains a little front-end knowledge and. NET interview in the various test centers, hoping to find a job for the students even a little help.
    • The ancients cloud " temperature so know new, can for the teacher ", I work more than three years, has been lazy to write a blog, the knowledge is only stored in the cloud notes, but also self-deception thought can be used, unfortunately put into the inside will not look again, the habit of keeping notes is there, but seldom go back to look at the habit. Over time, the more the heap, the nausea cycle, only the peace of mind, not the technology , for this, I decided to write more blog, not only to keep notes, but also to organize the concurrent out, so as to really consolidate.
    • The reader for this article is
    • [x] Newly graduated Meng Xin
    • [x] Work soon change work classmate

    • Daniel saw that this is the expression of the figure below, so you can give comments in the comment area 233.

Talk less, straight into the subject:

1.c# the difference between a value type and a reference type
difference detailed
The difference when assigning a value A variable of value type will get a true copy of the data directly, the initial value is 0, and the assignment to the reference type is simply to assign the object's reference to the variable, which may cause multiple variables to be referenced to an actual object instance with null values.
Differences in memory allocations An object of value type allocates memory on the stack, whereas an object of reference type allocates memory on the heap. The controls on the stack are relatively limited, but run much more efficiently than the heap.
The difference from the inheritance structure Because all value types have a common base class: System.ValueType, value types have a common nature that some reference types do not. A more important point is the comparison of value types the implementation of the Equals method has changed. All value types have implemented a comparison of content, whereas reference types still use reference comparisons without overriding the Equals method.
2. How to enable a type to be used in a foreach statement

1. To iterate through the collection, the collection must meet specific requirements.

    • For example, in the following foreach statement:
    • foreach (ItemType item in mycollection)
    • mycollection must meet the following requirements:
    • Collection type:
    • ①. Must be interface, class, or struct.
    • ②. You must include an instance method named GetEnumerator for the return type, such as enumerator.
      The enumerator type (class or struct) must contain:
      A property named current that returns ItemType or can be converted to a type of this type. The property accessor returns the current element of the collection.
      A bool method named MoveNext that increments the item counter and returns True if there are more items in the collection.

2. There are three ways to use collections:

    1. Use the instructions above to create a collection. This collection can only be used for C # programs.
    2. Use the instructions above to create a generic collection and implement the IEnumerable interface in addition. This collection can be used in other languages, such as Visual Basic.
    3. A predefined collection is used in the collection class.
What are the characteristics of 3.sealed modified classes?
    1. The sealed modifier is used to prevent other classes from being derived from the class being decorated. If a sealed class is specified as the base class for other classes, a compile-time error occurs.
    2. Sealed classes cannot be abstract classes at the same time.
    3. The sealed modifier is primarily used to prevent unintended derivation, but it also enables some runtime optimizations. Specifically, because sealed classes never have any derived classes, calls to virtual function members of instances of sealed classes can be converted to non-virtual calls to handle.
//Cs_sealed_keyword.csUsing system;sealedclasssealedclass{ Publicint x; Publicint y;}classmainclass{Static voidMain () {Sealedclass SC =NewSealedclass (); sc.x = the; SC.Y = Max; Console.WriteLine ("x = {0}, y = {1}", sc.x, SC.Y); }} Output X = the, y = MaxIn the preceding example, if you attempt to inherit from a sealed class by using the following statement:classMyderivedc:myclass {}//ErrorYou receive an error message:' Myderivedc 'Cannot inherit from sealedclass ' MyClass '.
4. Object-oriented 3 basic feature encapsulation
noun Introduction
Packaging Encapsulation is one of the object-oriented features and is the main feature of object and class concepts.

Package Details:

    • That is, the object is encapsulated into an abstract class, and the class can put its own data and methods only trusted class or object operation, to the untrusted information hiding.

      Inherited
      noun Introduction
      Inherited One of the main functions of object-oriented programming (OOP) language is "inheritance". Inheritance refers to the ability to use all the functionality of an existing class and to extend these capabilities without rewriting the original class.

Inheritance explained:

    • New classes created through inheritance are called "subclasses" or "derived classes."
    • The inherited class is called the base class, the parent class, or the superclass.
    • The process of inheritance is from the general to the special process.
    • To implement inheritance, it can be implemented through inheritance (inheritance) and combination (composition). In some OOP languages, a subclass can inherit multiple base classes. However, in general, a subclass can have only one base class, and to implement multiple inheritance, it can be implemented by multilevel inheritance.

There are three types of implementation of inheritance concepts: implementation inheritance, interface inheritance, and visual inheritance

    1. Implementation inheritance refers to the ability to use the properties and methods of a base class without additional coding;
    2. Interface inheritance refers to the ability to use only the names of properties and methods, but subclasses must provide the implementation;
    3. Visual inheritance is the ability of a subform (class) to use the appearance of a base form (class) and to implement code.
    4. When considering using inheritance, it is important to note that the relationship between the two classes should be a "belongs" relationship. For example, the Employee is a person and the Manager is a person, so these two classes can inherit the People class. But the Leg class cannot inherit the person class, because the leg is not a human.
    5. Abstract classes only define generic properties and methods that will be created by subclasses, and when creating abstract classes, use the keyword Interface instead of class.
      OO development paradigm is roughly: dividing objects → abstract classes → organizing classes into hierarchical structures (inheritance and compositing) → Designing and implementing several stages with classes and instances.
Polymorphic
noun Introduction
Polymorphic Polymorphism (POLYMORPHISN) is a technique that allows you to set a parent object to be equal to one or more of his child objects, after which the parent object can operate differently depending on the attributes of the child object currently assigned to it. To put it simply, it is a sentence: A pointer to the parent class type is allowed to be assigned a pointer to the child class type.

To achieve polymorphism, there are two ways to overwrite, overload :

    1. Overwrite refers to the practice of redefining the virtual function of a parent class by a subclass.
    2. overloading, which means that multiple functions with the same name are allowed, and the parameter tables of these functions are different (perhaps the number of parameters is different, perhaps the parameter types are different, perhaps the two are different).

So what is the role of polymorphism?

We know that encapsulation can hide implementation details and make code modular; Inheritance can extend existing code modules (classes); they are all designed to-code reuse. And polymorphism is for another purpose--interface reuse! The role of polymorphism is to ensure that classes are called correctly when inheriting and deriving a property of an instance of any class in the family tree.

5.. NET managed resources and unmanaged resource unmanaged Resources
    • The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file, window, or network connection, although the garbage collector can track the lifetime of an object that encapsulates an unmanaged resource, but it does not know how to clean up those resources. Fortunately, the. NET Framework provides the Finalize () method, which allows appropriate cleanup of unmanaged resources when the garbage collector reclaims that class of resources. If you search for Finalize in the MSDN Library, you'll find a lot of similar topics,

      There are several common unmanaged resources listed here: Applicationcontext,brush,component,componentdesigner,container,context,cursor,filestream,font, Icon,image,matrix,object,odbcdatareader,oledbdatareader,pen,regex,socket,streamwriter,timer,tooltip and so on resources. May be in use when a lot of did not notice!

Managed resources
    • Like simple int,string,float,datetime and so on, more than 80% of the resources in. NET are managed resources.
6.string str=null and string str= "" What's the difference?
    • You have defined a reference to a variable str

    • String Str=null points This reference to a null, where there is no value for the address, i.e. no memory space allocated

    • String Str= "" points this reference to an address in which an empty character is stored, which takes up memory space

What does 7.StringBuilder do?

description : String in the operation (such as assignment, stitching, etc.) will produce a new instance, and StringBuilder will not.
So it's best to use StringBuilder when a large number of string concatenation or frequent manipulation of a string, do not use string

In addition, for String we have to say a few more words:

1. It is a reference type that allocates memory on the heap

2. A new instance is generated when the operation is

3.String object once generated immutable (immutable)

4. Define equality operators (= = and! =) to compare the values of a String object (not a reference)

Summary :
StringBuilder constructs a string object efficiently using the idea of a constructor design pattern, StringBuilder can effectively avoid the generation of temporary string objects during the construction process. Once StringBuilder's ToString method is called, the resulting string is generated, and subsequent operations result in the assignment of a new string object. Because of the non-modifiable nature of the string object, StringBuilder is also often used to interact with unmanaged code.

8. What is the role of serialization

description : The flow type can be used to conveniently manipulate the various byte streams, but how to convert the existing instance object into a conveniently transmitted byte stream requires serialization technology.

Where to use 9.BASE64 encoding

description : BASE64 encoding is a coding method used to confuse plaintext by assigning the original 8-byte array order to a new 6-byte array, and then filling the high 2 bits of each byte with a new 8-bit byte array. The convert type in net can be used to perform conversions between Base64 strings and 8-bit byte arrays.

10. How does a string pool improve system performance?

Summary : Once the string pooling mechanism is used, a container is created internally when the CLR starts, and the container's key is the string content, and the value is a reference to the string on the managed heap. When a new string object needs to be allocated, the CLR first detects whether the character object is already contained within the inner container, and if it is already included, returns a string object reference that already exists: if it does not exist, a new string object is assigned and added to the internal container. However, this mechanism does not work when the program explicitly declares a newly allocated string object with the New keyword.

11.FileInfo and DirectoryInfo

Summary : FileInfo and DirectoryInfo Two types are available in. NET built-in types to manipulate files and folders, respectively. Unlike file and directory types, the main function of FileInfo and directory is to manipulate the structure of files and folders in the file system to perform functions such as creating, copying, reading information, moving, judging whether it exists, and deleting it.

12.datetime.parse (mystring) What's wrong with this line of code?

Summary : Use TryParse to avoid exceptions.

示例string time="2013-02-02";DateTime t;if(DateTime.TryParse(s,out t)){   //输出}
Similarities and differences of three comparative methods of 13.system.object
 static  bool  referenceequals  (object  A, object  B )  Static  bool  equals  ( object  A, object  B ) virtual  bool  equals  (object  obj )   

1.ReferenceEquals implements reference comparisons of types, as can be seen from parameter types, which can be used not only to compare two reference type objects, but also to compare two value type objects.
Of course, the ReferenceEquals method makes sense only if it is applied on a reference type, and a reference to the comparison value type will always return false, regardless of whether their values are equal. Even with the following example:
int i=0; Console.WriteLine(Object.ReferenceEquals(i,i));

Explanation: Because the above two I are boxed first, and then passed to the ReferenceEquals method.

2.Equals is another static comparison method that implements functionality that differs depending on the type. In fact, the function of the Equals method relies on the implementation of the Equals method, and in a nutshell, the content of the static Equals method is divided into two steps: first checking whether two objects are identical (= =), and then invoking an instance of one of the parameter objects equals method to determine whether two objects are identical.

How does the 14.GetHashCode approach work? When will this method be used?

Brief description :

    • The GetHashCode algorithm in object guarantees that the same object returns the same hashcode, while different objects return different hashcode, but the default GetHashCode algorithm is incorrect when objects equal to the value type are of equal object type.
    • Overriding GetHashCode must ensure that the same object returns the same Hashcode value at any time, while equal objects must return the same value, and on that basis, ensure that the hascode is randomly distributed as much as possible.
15. Principle of Delegation

Summary : A delegate is a class of types that inherit from System.Delegate, and each delegate object contains at least one pointer to a method, either an instance method or a static method. Delegates implement the mechanism of callback methods to help programmers design more concise and graceful object-oriented programs.

16. What is the difference between a delegate callback static method and an instance method

Summary : What is the difference between a delegate callback static method and an instance method when a delegate binds a static method, the internal object member variable _target is set to null, and when the delegate binds an instance method, _target sets exponentially to an instance object of the type to which the instance method belongs. When the delegate is executed, the object instance is used to invoke the instance method.

17. What is a chained delegate?

Summary : A chained delegate is a list of a delegate, not another special kind of delegate. When a method on the chain is executed, subsequent delegate methods are executed sequentially. System.multicast delegate defines the support for chained delegates. On the basis of System.Delegate, it adds a pointer to the subsequent delegate, thus implementing a simple list structure.

18.asp.net operating mechanism 1. How the browser interacts with the server
    1. Popular Description: We usually through the browser to access the site, in fact, you visit a computer through a browser to access the file, but the browser's access request is accessed by a Web server software on the computer to receive processing, it will analyze the received request information, In order to follow the request information to find files on the server computer, processed, and eventually send the generated content back to the browser.
    2. Simply put: By the browser generated a "command", the Internet to another computer software (server software), the Server Software received "command", the analysis to understand the "command", and then follow the "command" to locate the file on the server computer, the file content sent back to the browser.

    1. Through, we see a simple process of browser and server interaction. Now, we have to think about the browser and server Software is God horse East, how do they interact with information?
    2. In fact, the browser and server software is two separate applications (just like QQ, Office, paint tools). The interaction between the two applications involves the application communication problem. What about the way they communicate with God's horse?
    • The answer is socket:socket. As for the specific use and principle of the socket, the space problem is not written in this article, the first reserved location in this, the next time to fill in the "multi-threaded and socket-based simple webserver software-no control of ASP."
    • Browsers and server software send and receive information through sockets, but the key question now is what they send and receive?---HTTP protocol-based message data (see "HTTP protocol Introduction---ASP. NET with no controls").
    • That is, the browser and server software is actually two of the two applications that use the socket to communicate: Both parties send data organized according to the HTTP protocol syntax specification, and after receiving the data are interpreted in accordance with the HTTP protocol syntax specification.

      2. Browser and IIS (or other webserver) interaction mechanism

is IIS (Server software)

1. Browser and IIS interaction process:
We all know that on the Internet to determine the location of a computer using IP addressing, but why when we usually visit the site directly into a domain name can also access to a server computer and then by the other party's server software to send response page data to me? I'll list the simple steps below:

(1) In the browser input URL: www.oumind.com/index.html, the browser according to the HTTP protocol syntax to generate the request message data.

(2). The browser checks to see if the www.oumind.com/index.html. Domain name corresponds to the server IP address. If not, it sends the request to the nearest DNS server in the city network (the domain name resolution Server), which will be sent back to the server according to the domain name we send to the IP address of the domain name, and then send to the browser.

(3) The browser obtains the server computer IP corresponding to the www.oumind.com/index.html domain name from the DNS server, then sends the request message through the socket to the server computer. (Note: The HTTP protocol specifies that the default port used by the server software is 80, in layman's terms, that is, if the browser accesses a Web site page, the browser by default is to send the request message to server 80 port, and the server is responsible for monitoring the port software is generally server software- For example, the Iis,java tomcat used by ASP. )

(4) IIS receives the request message, parses the request packet, and obtains the requested page path from the/index.html. Determine the suffix name of the page, and if it is a static page (. Html/.jpg/.css/.js, etc.), the contents of the file are read directly by the components of the IIS software, and the content is sent back to the browser via the socket.

(5) But if a dynamic page (. aspx/.ashx) is requested at this time, IIS will not be able to handle it itself (because the IIS software was developed when ASP. NET program does not exist yet). So, IIS goes to its extender mapping table to see if there are extensions that can handle such files based on the requested file suffix name.

The files that are commonly used in our ASPNET are aspnet_isapi.dll. Aspx/.ashx and other corresponding handlers. Such as:

(6) If IIS finds the corresponding handler based on the suffix, it calls the program to process the request message sent by the browser.

IIS itself cannot handle pages such as the ASPX extension, and can only request static files such as HTML to handle pages with an ASPX extension because IIS has an ISAPI filter, which is a COM component.

Asp. NET service when registering to IIS, a Win32 Extended dynamic library Aspnet_isapi.dll is added. and registers the extension with a page extension (such as ASPX) that can be processed inside IIS. After the extension is started, pages that are not processed by IIS are handled in a defined way.

When a client requests a server resource, This HTTP request is intercepted by the Inetinfo.exe process (WWW service), then the check requests the type of the resource and assigns the requested resource to a specific handler module based on the resource mapping information, which is stored in the IIS Meta-Library, an IIS-only configuration database. If the requested static resource (img,text,html, etc.) is handled by IIS (IIS accesses the requested file on the local Web server), the content is output to the console, and the requesting browser is able to receive it.

If a request is to be processed on the server side, it will be uploaded to the registered extension, and the ASPX request will be assigned to Aspnet_isapi.dll, allowing the program to start processing the code, generate standard HTML code, and then add the HTML to the original HTML. Finally, the full HTML is returned to Iis,iis and the content is sent to the customer's browser.

The ASP. NET Framework handles the request :

It says that IIS assigns a page like aspx to Aspnet_isapi.dll, which is then handled as follows:

1. Aspnet_isapi.dll will send this HTTP request to W3wp.exe via an HTTP pipeline pipeline (the IIS worker process, called w3wq.exe,iis5.0 in IIS6.0), This HTTP request is then processed by the ASP. HttpRuntime.

2. httpruntime first determines the class name for processing the request, and httpruntime calls the class through the public interface IHttpHandler to obtain an instance of the class of the requested resource.

3. Call Httpruntime.processrequest to start processing the page to be sent to the browser, specifically to create an HttpContext instance that encapsulates all the HTTP-specific information about the request and initializes a write object for caching the tag code.

4. httpruntime uses contextual information to find or create a new object that can handle the request's Web application. The HttpApplication factory is responsible for returning the HttpApplication instance.

5. The HttpApplication instance reads the configuration of all HttpModule in Web. config.

6. The HttpApplication object uses an instance of the IHttpHandlerFactory type to return the HttpHandler (HTTP handler) to the HttpRuntime object. A page is just an HTTP handler object.
7. The ProcessRequest method that finally calls IHttpHandler's Page object by the HttpRuntime object.

What is the use of static variables and methods in 19.c# 1. Introduction to static variables

In a C # program, there is no concept of a global variable, which means that all member variables can manipulate the data only if it is an instance of that class, which plays a role in "information hiding." But sometimes it's not a wise choice.

    • Suppose we want to define a book class that requires the class to hold the number of books, that is, each additional book (defining an instance), the number of books should be added by 1. If there is no static variable, we need to keep the number of books in each book (instance), however, such variables to be stored in different books (instances), the number of books (instances), we can accept, if the number of books (examples), such as thousands, We can't imagine how much resources (such as memory, disk space) can be wasted, and what's even more unbearable: because the number of books (instances) is kept in every book (instance), the value is definitely different. To match the number of books (instances) saved in these books (instances), we must modify the values that are saved in all other books (instances) when each additional new book is generated (creating a new instance).
    • Oh,my god! you will re-aspire to process-oriented program design approach, yearning to have global variables of the era. However, this situation does not occur because you have another variable type in C #: a static variable. It is like a global variable in a class that holds the public information for a class, and all instances (objects) of that class share the value.

Static variables are declared in the following way:

  static 数据类型 变量名;

The access modifier here, like other members of the class, can be public,protected,private or internal, and so on.

2. How do static variables work?

Static variables must be referenced using the class name, not an instance of the class, because static variables are not part of any instance, but are common.

    • We can make an analogy: in a class, some items are personal, we want to use, we must point out the owner of the item, such as "Wang San Bike", in C # program we can use: Wang San. bike format. Some items are common items, can not be used in the name of the individual, but used in the name of the class, such as the collective contribution to buy basketball, can only say: "Class basketball", and can not say: "Wang San basketball." This is absolutely not possible, it is absolutely unfair to others, we can think of many corrupt officials are using things that do not belong to themselves, or in the personal name of the use of public things and ruined themselves.
    • A useful thing to say is that a static variable refers to it by using the class name. That is: class name. static variable name;

Here is a concrete example:

usingSystem;class Staticvar{ Public intX Public Static intYPublic   void printinfo(){Console.WriteLine ("non-static variable x={0}", x); Console.WriteLine ("static variable y = {0}", y); }        }class Test{ static void Main(string[] args){Staticvar STV =NewStaticvar (); stv.x =Ten;//stv.y =//error; cannot access static member "STATICVAR.Y" using instance reference; Use type name to qualify itSTATICVAR.Y = -; Stv.                   Printinfo (); }        }

Part of the program that is commented on: Stv.y = 20 is using an instance to refer to a static variable, which throws an error.

In addition, I would like to say that for static variables when declaring, if not given the initial value or not assigned any value before use, the system will give them a default value: For the integer data default is 0, the single-precision data is: 0.0f, double precision data is 0.0, the Boolean data is false, the reference data is null.

3. Static methods

Static methods, like static variables, do not belong to any particular instance, and are common to all members of the class and are called by the class name.

But pay attention to the following points:

    1. A static method can only access static members of a class and cannot access non-static members of a class;
    2. A non-static method can access a static member of a class, or it can access a non-static member of a class;
    3. Static methods cannot be invoked using an instance, only by using the class name.

Here is a concrete example to illustrate:

usingSystem;namespace teststatic{class statictest{intXStatic intYPublic   statictest(int A,int b){x = A;                     y = b; }Public   void simpleprint(){Console.WriteLine ("x="+x+", y="+y); }Public   static void staticprint(){Console.WriteLine ("Y={0}", y);//Console.WriteLine ("X={0}", x); Non-static members cannot be used in static methods}            }class Test{ static void Main(string[] args){Statictest St =NewStatictest (Ten, at); St. Simpleprint ();//st.        Staticprint (); Static methods cannot use instances to invokeStatictest.staticprint (); }             }        }

"New chapter of 2017". NET face Question Summary (i)

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.