C # basic concepts question 25-transfer from-tomyifeng personal space

Source: Internet
Author: User

C # basic concepts question 25 -- transfer from -- tomyifeng personal space

C # basic concepts 25 question

When I first learned C #, I asked a person about the data type and the branch statement and started the project. In the past two days, I have thoroughly read the relevant basic knowledge (learning and learning) and summarized 25 questions:

1. What are the differences between static and non-static members?
2. What is the difference between const and static readonly?
3. What does extern mean?
4. What does abstract mean?
5. What is the role of the Internal modifier?
6. What is the sealed modifier?
7. What is the difference between override and overload?
8. What is an index indicator?
9. What is the role of the new modifier?
10. What is the meaning of this keyword?
11. Can I use Abstract Functions to override virtual functions in the base class?
12. Can there be virtual functions in the seal class?
13. What is an attribute accessor?
14. can abstract be used with virtual? Can it be used with override?
15. What members can an interface contain?
16. What is the difference between classes and structures?
17. What problems does interface multi-inheritance bring about?
18. What is the difference between an abstract class and an interface?
19. What is an alias indicator?
20. How to manually release resources?
21. P/invoke?
22. What is the difference between stringbuilder and string?
23. What is the meaning of explicit and implicit?
24. What is the use of Params?
25. What is reflection?

The following is my reference answer (within the scope of C # Language). If it is inaccurate or not comprehensive, you are welcome to correct it!

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

A:

Static variables are declared using the static modifier. They are created when the class is instantiated and accessed through the class.

Variables declared without the static modifier are called non-static variables. They are created when the object is instantiated and accessed through the object.

The same static variable of all instances of a class is the same value. The same non-static variable of different instances of the same class can be different values.

Non-static members, such as non-static variables and non-static functions, cannot be used in the implementation of static functions.

Example:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example01
{
    class Program
     {
        class Class1
         {
            public static String staticStr = "Class";
            public String notstaticStr = "Obj";
         }
        static void Main(string[] args)
         {
// Static variables are accessed by class. The same static variables of all instances of this class are the same value.
             Console.WriteLine("Class1's staticStr: {0}", Class1.staticStr);
 
             Class1 tmpObj1 = new Class1();
             tmpObj1.notstaticStr = "tmpObj1";
             Class1 tmpObj2 = new Class1();
             tmpObj2.notstaticStr = "tmpObj2";
 
// Non-static variables are accessed through objects. The same non-static variables of different objects can have different values.
             Console.WriteLine("tmpObj1's notstaticStr: {0}", tmpObj1.notstaticStr);
             Console.WriteLine("tmpObj2's notstaticStr: {0}", tmpObj2.notstaticStr);
 
             Console.ReadLine();
         }
     }
}

Result:
Class1's staticstr: Class
Tmpobj1's notstaticstr: tmpobj1
Tmpobj2's notstaticstr: tmpobj2

2. What is the difference between const and static readonly?

A:

Const

The member declared with the const modifier is called a constant, Which is initialized during the compilation and embedded into the client program.

Static readonly

The member declared with the static readonly modifier is still a variable, but it has a usage similar to a constant: it can be accessed through a class and cannot be modified after initialization. But unlike constants, this variable is initialized at runtime.

Example:

Test class:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example02Lib
{
    public class Class1
     {
        public const String strConst = "Const";
        public static readonly String strStaticReadonly = "StaticReadonly";
        //public const String strConst = "Const Changed";
        //public static readonly String strStaticReadonly = "StaticReadonly Changed";
     }
}
 
Client code:
 
using System;
using System.Collections.Generic;
using System.Text;
using Example02Lib;
 
namespace Example02
{
    class Program
     {
        static void Main(string[] args)
         {
// After modifying the initial strconst value of class1 in example02, compile only the example02lib Project
// Check the newly compiled example02lib.dllbeibeibeibeiexample02.exe.pdf in the resource manager to execute example02.exe.
// Do not directly debug and run in IDE because this will recompile the entire solution !!
 
// You can see that the output of strconst has not changed, and the output of strstaticreadonly has changed
// Indicates that the const variable is initialized and embedded in the client program during the compilation period, while staticreadonly is initialized at the runtime.
             Console.WriteLine("strConst : {0}", Class1.strConst);
             Console.WriteLine("strStaticReadonly : {0}", Class1.strStaticReadonly);
 
             Console.ReadLine();
         }
     }
}

Result:
Strconst: const
Strstaticreadonly: staticreadonly

EXAMPLE After modification:

Test class:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example02Lib
{
    public class Class1
     {
        //public const String strConst = "Const";
        //public static readonly String strStaticReadonly = "StaticReadonly";
        public const String strConst = "Const Changed";
        public static readonly String strStaticReadonly = "StaticReadonly Changed";
     }
}

Result

Strconst: const
Strstaticreadonly: staticreadonly changed

3. What does extern mean?

A:

The extern modifier is used to declare member functions implemented outside the assembly.

It is often used to call system API functions (through dllimport ). Note: The static modifier must be added for use with dllimport.

It can also be used for calling components of different versions of the same assembly (using extern to declare aliases)

Cannot be used together with abstract Modifier

Example:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
 
namespace Example03
{
    class Program
     {
// Note that dllimport is an attribute property defined in the system. runtime. interopservices namespace.
// A static modifier must be added when the extern and dllimport are used together.
         [DllImport("User32.dll")]
        public static extern int MessageBox(int Handle, string Message, string Caption, int Type);
 
        static int Main()
         {
            string myString;
             Console.Write("Enter your message: ");
             myString = Console.ReadLine();
            return MessageBox(0, myString, "My Message Box", 0);
         }
     }
}

Result:

4. What does abstract mean?

A:

Abstract modifiers can be used for classes, methods, attributes, events, and index indicators (Indexer) to represent abstract members.

Abstract cannot be used with static or virtual

The declared abstract member does not include the implementation code. However, as long as there are still unimplemented abstract members (that is, abstract classes) in the class, its objects cannot be instantiated, it is usually used to force the inheritance class to implement a certain member.

Example:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example04
{
# Region base class, abstract class
    public abstract class BaseClass
     {
// Abstract attribute. The get and set accessors indicate that the inherited class must implement the attribute as read/write.
        public abstract String Attribute
         {
             get;
             set;
         }
 
// Abstract method. Input a string parameter without returning a value
        public abstract void Function(String value);
 
// Abstract event. The type is the predefined system proxy (delegate): eventhandler.
        public abstract event EventHandler Event;
 
// Abstract index indicator. Only get accessors indicate that the index indicator must be read-only for the inherited class.
        public abstract Char this[int Index]
         {
             get;
         }
     }
    #endregion
 
# Region inheritance class
    public class DeriveClass : BaseClass
     {
        private String attribute;
 
        public override String Attribute
         {
             get
             {
                return attribute;
             }
             set
             {
                 attribute = value;
             }
         }
        public override void Function(String value)
         {
             attribute = value;
            if (Event != null)
             {
                 Event(this, new EventArgs());
             }
         }
        public override event EventHandler Event;
        public override Char this[int Index]
         {
             get
             {
                return attribute[Index];
             }
         }
     }
    #endregion
 
    class Program
     {
        static void OnFunction(object sender, EventArgs e)
         {
            for (int i = 0; i < ((DeriveClass)sender).Attribute.Length; i++)
             {
                 Console.WriteLine(((DeriveClass)sender)[i]);
             }
         }
        static void Main(string[] args)
         {
             DeriveClass tmpObj = new DeriveClass();
 
             tmpObj.Attribute = "1234567";
             Console.WriteLine(tmpObj.Attribute);
 
// Associate the static function onfunction with the event of the tmpobj object
             tmpObj.Event += new EventHandler(OnFunction);
 
             tmpObj.Function("7654321");
 
             Console.ReadLine();
         }
     }
}

Result:
1234567
7
6
5
4
3
2
1

5. What is the role of the Internal modifier?

A:

The internal modifier can be used for types or members. types or members declared using this modifier can only be accessed within the same set.

The interface member cannot use the internal modifier.

It is worth noting that if the protected modifier is added to the internal Member, the access level is internal or protected. It is easy to make a mistake to look at the literal meaning. Many people think that internal protected should be "only accessible to sub-classes in the same assembly", but it actually means "all classes in the same assembly, and all subclasses in the Assembly can access"

Example

Class1 of example05lib

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example05Lib
{
    public class Class1
     {
        internal String strInternal = null;
        public String strPublic;
        internal protected String strInternalProtected = null;
     }
}

Result
The class2 class of the example05lib project can access the strinternal member of class1, but also the strinternalprotected member because they are in the same set of programs.

The class3 class in the example05 project cannot access the strinternal members of class1 because they are not in the same assembly. However, you can access the strinternalprotected member because class3 is an inherited class of class1.

The program class of the example05 project cannot access the strinternal members of class1 or strinternalprotected members because they are neither in the same Assembly nor have an inheritance relationship.

 

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.