. NET face question 5

Source: Internet
Author: User
Tags closure constant definition

Common Interview Topics:

1. What is the difference between const and readonly?

2. What types can be defined as constants? What is the risk of constant const?

3. What are the similarities and differences between fields and attributes?

4. What are the differences between static and non-static members?

5. What are the risks of automatic attributes?

6. What are the features? How to use?

7. What results does the following code output? Why?

list<action> ACS = new list<action> (5), for (int i = 0; i < 5; i++) {    acs. ADD (() = {Console.WriteLine (i);}); Acs. ForEach (ac + = AC ());

8. What is a delegate in C #? Is the event a delegate?

The Vendetta constants for fields and properties

The basic concepts of constants are not discussed in detail, and some features of constants are summarized as follows:

    • The value of a constant must be determined at compile time, simply because the definition is a set value and will not be changed later, she is a compilation constant.
    • Constants can only be used for simple types, because constant values are to be compiled and then saved to the Assembly's metadata, only primitive types such as int, char, string, bool, double, and so on are supported.
    • Constants are used to inline the value of a constant into the IL code, and the constant is similar to a placeholder, and is replaced at compile time. It is this feature that leads to a risk of constants that do not support cross-assembly version updates;

For constants that do not support cross-assembly version updates, give a simple example to illustrate:

public class a{Public    const int PORT = 10086;    public virtual void Print ()    {        Console.WriteLine (a.port);    }}

The above is a very simple code, its production of IL Code is as follows, in the use of constant variables where the value of her copy (the value of the constant is linked to the place of use), and the constant variable a.port is not related. If a refers to a constant in the B assembly (B.dll file), if you modify the constant value in the B assembly separately, just recompile B, and do not compile assembly A, there is a problem, that is, the cross-assembly version update is not supported. After the constant value is updated, all code that uses the constant must be recompiled, which is an issue that we must pay attention to when using constants.

    • Do not arbitrarily use constants, especially data that may change;
    • Do not arbitrarily modify the defined constant value;
Add the nature of the enumeration

Then the above const says that enum Enum also has a similar problem, its root and const, look at the code you understand. The following is a simple enumeration definition, and her IL code definition is the same as the const definition! The enumeration has the same member definition as the constant definition, so the enumeration is inherently quite a constant collection.

public enum enumtype:int{    none=0,    int=1,    string=2,}

About Fields

The field itself is nothing to say, here is a field of inline initialization problem, it may be easy to overlook a small problem (but it doesn't seem to affect), first look at a simple example:

public class sometype{    private int age = 0;    Private DateTime StartTime = DateTime.Now;    private string Name = "three Bodies";}

Defining fields and initializing values is a common code-writing habit. But notice, look at the IL code structure, a line of code (definition field + Assignment) is split into two pieces, the final assignment is executed in the constructor.

So the problem is, if you have more than one constructor, as in the following, there are more than half of the constructors that will cause the IL code to be assigned to the field in two constructors. ctor, which creates unnecessary code bloat. This is also a good solution, add a ": This" after the non-default constructor, or display the initialization field in the constructor.

public class sometype{    private DateTime StartTime = DateTime.Now;    Public SomeType () {} public    SomeType (string name)    {                    }}
Nature of attributes

Attributes are the basic concepts of object-oriented programming, providing access encapsulation of private fields, and the use of the get and set accessor methods in C # for the operation of readable writable properties, providing a secure and flexible data access encapsulation. Let's look at the nature of the attribute, the main means or the IL code:

public class sometype{Public    int Index {get; set;}    Public SomeType () {}}

The properties defined above index are divided into three parts:

    • Auto-generated private field "<index>k__backingfield"
    • Method: Get_index (), get field value;
    • Method: Set_index (Int32 ' Value '), set the field value;

Therefore, it can be said that the nature of attributes or methods, using object-oriented ideas to encapsulate the field. When defining a property, we can customize a private field or use the automatic attribute "{get; set;} "In simplified syntax form.

One thing to be aware of when using automatic attributes is that private fields are automatically named by the compiler and are not controlled by the developer. As a result of this problem, I have encountered a bug in project development:

This bug is about serialization, there is a class that defines many (automatic) attributes, and the information for this class needs to be persisted to the local file, when it was used. NET comes with a binary serialization component. Later, because of a change in requirements, one of the fields modified, you need to change the automatic attributes to their own named Private field properties, as in the following example. Test serialization to local no problem, deserialization is not a problem, but the final bug is still tested, the problem before deserialization (before modifying the code) of the local file, the value of the Index property is missing!!!

private int _index;public int index{    get {return _index;}    set {_index = value;}}

Because the nature of the property is the method + field, the real value is stored on the field, the name of the field is changed, the corresponding field is not found when deserializing the previous file, resulting in the loss of the value! This is the possible risk of using automatic attributes.

Delegates and events

What is a delegate? In simple terms, a delegate is similar to a function pointer in C or C + +, allowing the method to be passed as a parameter.

    • Delegates in C # inherit from the System.Delegate type;
    • The declaration of a delegate type is similar to a method signature, with return values and parameters;
    • A delegate is a reference type that can encapsulate a named (or anonymous) method, passing a method as a pointer, but the delegate is object-oriented, type-safe;
The nature of a delegate--is a class

. NET does not have a function pointer, the method is impossible to pass, the delegate can be passed like a normal reference type, because she is essentially a class. The following code is a very simple custom delegate:

public delegate void Showmessagehandler (string mes);

Look at the IL code she produced.

We define a delegate's code in a row, and the compiler automatically generates a bunch of code:

    • The compiler automatically helped us create a class Showmessagehandler, inherited from System.MulticastDelegate (she inherits from System.Delegate), which is a multicast delegate;
    • The delegate class Showmessagehandler contains several methods, the most important of which is the Invoke method, the signature and the method signature of the definition are consistent;
    • The other two versions of BeginInvoke and EndInvoke are asynchronous execution versions;

Therefore, it is not difficult to guess, when we invoke the delegate, is actually called the delegate object's Invoke method, you can verify that the following call code will be compiled to the delegate object Invoke method invocation:

Private Showmessagehandler showmessage;//calls this. ShowMessage ("123");

. NET closures

Closures provide a script-like language for functional programming that is convenient and can share data, but there are also some pitfalls.

The 7th question in the list of topics is one. NET closure problems.

list<action> ACS = new list<action> (5), for (int i = 0; i < 5; i++) {    acs. ADD (() = {Console.WriteLine (i);}); Acs. ForEach (ac + = AC ()); The output is 5 5 5 5 5, all 5? This must not be what you want! What is this for?

The action in the code above is. NET a delegate with no parameter and no return value defined for us, from the previous section we know that the principal is a class, understanding this is the key to solve the problem. In this place, the delegate method share uses a local variable i, what is the generated class like? Look at the IL code:

The shared local variable is promoted to a field of the delegate class:

    • The life cycle of the variable i is prolonged;
    • The value of field I at the end of the For loop is 5;
    • The subsequent invocation of the delegate method, is definitely the output 5;

So how do we fix it? Very simply, the delegate method uses a temporary local variable to be OK and does not share the data:

list<action> acss = new list<action> (5); for (int i = 0; i < 5; i++) {    int m = i;    AcSS. ADD (() = {Console.WriteLine (m);}); AcSS. ForEach (ac + = AC ()); Output 0 1 2 3 4

As for the principle, you can explore it yourself!

Answer to the question: 1. What is the difference between const and readonly?

The const keyword is used to declare a compile-time constant, and ReadOnly is used to declare run-time constants. can identify a constant, mainly the following differences:
1, the initial position is different. The const must be assigned at the same time as the declaration, ReadOnly can be assigned at the declaration, or it can be assigned in the constructor method.
2. Different decoration objects. A const can modify a field of a class, or it can modify a local variable; readonly can only decorate a field of a class.
3. Const is a compile-time constant, which determines the value at compile-time, and the value is inline in the code at compilation, and ReadOnly is the run-time constant that determines the value at runtime.
4, the const default is static, and readonly if set to static need to display the declaration.
5. When the supported types are different, const can only modify the primitive type or other reference types with a value of NULL; ReadOnly can be of any type.

2. What types can be defined as constants? What is the risk of constant const?

Primitive type or other reference type with a value of NULL, the risk of a constant is that cross-assembly version updates are not supported, and all code that uses that constant must be recompiled after the constant value is updated.

3. What are the similarities and differences between fields and attributes?
    • Properties provide more powerful, flexible functionality to manipulate fields
    • Fields are not generally designed to be public due to object-oriented encapsulation
    • property allows code to be written in set and get
    • Properties allow you to control the accessibility of set and get, providing read-only or read-write functionality (logically write-only is meaningless)
    • Properties can use the override and new
4. What are the differences between static and non-static members?
    • Static variables are declared with the static modifier, and static members are loaded when the class is added (as mentioned in the previous article, static fields are stored on the load heap with the type Object) and accessed through the class.
    • Variables declared without the static modifier are called non-static variables, created when an object is instantiated, accessed through an object.
    • The same static variable for all instances of a class is the same value, and the same non-static variable of a different instance of the same class can be a different value.
    • Static functions cannot be implemented with non-static members, such as non-static variables, non-static functions, and so on.
5. What are the risks of automatic attributes?

Because the private field of the automatic attribute is named by the compiler, it should not be modified at any later stage, such as the loss of field values in serialization.

6. What are the features? How do I use it?

Attributes and attributes are two concepts that are completely different, but similar in name. The attribute feature is a piece of configuration information associated with a target object, essentially a class that provides associated additional information to the target element that is stored in the DLL's metadata, which itself has little meaning. The runtime obtains additional information in a reflective manner. Use the method can refer to: http://www.cnblogs.com/anding/p/5129178.html

7. What results does the following code output? Why?
list<action> ACS = new list<action> (5), for (int i = 0; i < 5; i++) {    acs. ADD (() = {Console.WriteLine (i);}); Acs. ForEach (ac + = AC ());

The output is 5 5 5 5 5, all 5! Because the shared variable I in the closure is promoted to the public field of the delegate object, the life cycle extends

8. What is a delegate in C #? Is the event a delegate?

What is a delegate? In simple terms, a delegate is similar to a function pointer in C or C + +, allowing the method to be passed as a parameter.

    • Delegates in C # inherit from the System.Delegate type;
    • The declaration of a delegate type is similar to a method signature, with return values and parameters;
    • A delegate is a reference type that can encapsulate a named (or anonymous) method, passing a method as a pointer, but the delegate is object-oriented, type-safe;

Events can be understood as a special kind of delegate, and events are implemented internally based on delegates.

All rights reserved, article source: http://www.cnblogs.com/anding

Personal ability is limited, the content of this article is only for study, discussion, welcome correction, Exchange.

. NET face question 5

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.