such as Peng Web study notes (three). NET Advanced Technology

Source: Internet
Author: User
Tags modifiers object serialization shallow copy uppercase letter

NET Advanced Technology

One, multi-project development
1, add a reference to the project
Create a new class library that will be used to put the public to use the class, when using other items to reference it
Using class library file;

Note: Note that the referenced class is to be decorated with public
The modifiers of the classes in the referenced assembly, if not written, are internal by default.
The effect is that only the current assembly (class library) can be accessed inside.

2, multi-project time configuration file read problem
A, only the configuration file for the main project will work (currently started)
B,config file can not be renamed, can not build multiple config, in config also can not build multiple appsettings segments

3, in the project "Go To Definition", is not see the source code, you can use the Anti-compilation tool to view

4, methods for invoking third-party DLLs (class library files)
A, your own project uses a reference method between projects
b, use a DLL that someone else has written: Add Reference-Browse-Select the DLL file to add


Second, indexer Indexer
1, Indexer: No name, internal nature of the indexer

2, can be read-only or write-only

3, why the string can only char ch = s[5]; not s[5] = ' a '
The immutability of the string;
Read-only Index

public char this[int Index]{get;}


Third, closed class and Static class

1, sealed class sealed

Cannot have subclasses. Applies to basic classes in the system, such as the String class. can be new object

2, static class declared as static

Cannot create object, cannot create child class, can declare static member (method or variable)
Applies to tool classes, does not need new, calls its static methods or properties directly

3, extension method
How to use:
Declares a static class, adds a static method, the first parameter is the extended type, is marked as this,
It can then be called directly in other classes, or it can be called using a normal static method, so the private and protected members cannot be accessed.

Four, deep copy, shallow copy
1, refer to the same object when assigning a value to a reference type object variable

2, you can assign a new object by customizing a copy method

3, if there is a reference relationship between the objects, if the copy of the object is a shallow copy of the reference, if the referenced object is also copied a copy is a deep copy

Copy a reference to an object, called a shallow copy.
If the referenced object is also copied, it is called a deep copy.

V. Structural struct

is a value type, copy copy, cannot inherit, one struct cannot inherit from another struct or class. However, structs inherit from the base class object

struct person
{
public int age{get;set;}
Public String Name{get;set;}
}

Vi. value types and reference types
The difference between the two:
The assignment of a reference type variable copies only the reference to the object, and the reference type is in heap memory (malloc);

A value type variable assignment copies a copy, and the value type is in the stack memory;

The value type must be sealed;


Seven, CTS,CLS,CLR, garbage collection GC

Common type systems Cts,common type System

General Language Specification Cls,common Language specification

Common language runtime Clr,common Language runtime

Garbage collection GC, garbage Collection

1,. Net platform is not only the C # language, there are vb.net, F # and other languages. Il is a binary code (managed code) that the program eventually compiles to execute
Different languages are eventually compiled into standard Il (intermediate language, MSIL), so that C # can invoke vb.net written assemblies (Assembly,dll, EXE)
Under the. NET Platform: Different languages can be interconnected and call each other

2, the data types in different languages vary, such as integer type in vb.net, Integer, C # is int.
. NET platform specifies a common data type (Cts,common type System), each language compiler translates the type of its language into a type in the CTS.
int is a type in C #, Int32 is a type in the CTS, and int is a keyword in C #, but Int32 is not

3, different language syntax, such as the definition of a Class A inherits from B C # syntax is Class A:B{},VB. The syntax for net is class A Inherits B.
. NET platform specifies the common language specification (CLS, Common Language specification)

The 4,il code is run by the common language runtime (CLR, Common Language Runtime),
The CLR provides garbage collection
(GC, Garbage Collection, no reference objects can be automatically recycled, when the analysis can be recycled), JIT (instant compiler);

5, the value type is placed in "stack memory", the reference type is placed in "heap memory", the stack memory is automatically released after the end of the method, "heap memory" requires a GC to recycle

Eight, packing and unpacking

When a value type is assigned to a variable of type object, boxing occurs: wrapped as Object

When an object type variable is assigned to a value type, a unboxing occurs and a display conversion is required.

int i = 10;//value type Assignment
Object obj = i;//Boxing, no display conversion required, belongs to implicit conversion
Int J = obj;//Here error, occurrence unboxing, need to display conversion//int j = (int) obj;

Note: When unpacking, be sure to display the conversion back to the boxed data type, or will error!!

Nine, the question of comparison equal

1, see if two objects are the same object: Object 1. Refrenceequals (object 2);

The = = Method of the 2,string object is just a comparison!

The Equals method of the 3,object also compares whether the two variables point to the same object, and if the object is override the Equals method, it can make the same comparison of the content

4, by default = = is not called by the Equals method and requires the = = operator

5,string such as these classes are overridden by the Equals method

X. String buffer pool

1, because the string is immutable, once the string is declared, it will persist until the GC is judged to be unused and is recycled

2, string is a reference type, there will be a large number of string objects in the program, wasting memory, causing poor performance,

So the CLR provides a "string buffer pool", if you find the same content of the string object, and then declare it, take the original object directly
(Reuse of String objects)

string S1 = "Rupeng";
String s2 = "Rupeng";
string s3 = "Ru" + "peng";
String S4 = new String (S1. ToCharArray ());
String S5 = new String (new char[]{' R ', ' U ', ' P ', ' e ', ' n ', ' G '});
Console.WriteLine (Object.referenceequals (S1,S2));//true, the role of a string buffer pool, two string references to the same object
Console.WriteLine (Object.referenceequals (S1, S3));//true, compiler optimization, stitching first, then assigning value
Console.WriteLine (Object.referenceequals (S1, S4));//false
Console.WriteLine (Object.referenceequals (S1, S5));//false
Console.WriteLine (Object.referenceequals (S4, S5));//false

Xi., ref and out

Modifiers for ref method parameters
1, the method internally modifies the direction of the external variable;

2, the variable must be assigned before it is passed in;

3, the method must not be assigned;

Modifiers for Out method parameters

1, when the method requires multiple return values, use the

2, the variable does not have to be assigned before the value, the assignment is useless

3, the parameter must be assigned in the method

12. Commission

1, a delegate is a data type that points to a method; a delegate is a reference type, and a variable can be null

2, the way to declare a delegate:

Delegate returns a value type delegate name (parameter 1, parameter 2, ...). ); For example: delegate void Mydel (int n)

Note: In addition to the previous delegate, the remainder is the same as declaring a function, but Mydel is not a function name but rather a delegate type name

3, you can declare a variable that points to a method that is compatible with its type

4, how to create an object of the delegate type:

Mydel sp = new Mydel (SayHello);
Attention:
The SayHello needs to be the same as the Mydel parameter and the return value;
SP This delegate variable points to SayHello this method, do not write new Mydel (SayHello ()), because plus () is called method

5, simplified method:

Mydel SP = sayhello;//compiler will get into new Mydel (SayHello)

Be careful not to write Mydel sp = SayHello ();

6, use of the delegate:

A delegate variable can be assigned to each other, which is a process of transmitting a pointing method;

SP () is the method that the call points to, and if parameters are passed

code example:
public delegate void Mydel (int n);//First step, declare a delegate

static void M1 (int a)//defines a method with the parameter and return value of the method corresponding to the delegate
{
Console.WriteLine ("M1" +a);
}

Mydel D1 = new Mydel (M1);//declares a variable of type Mydel, pointing to an object that points to the M1 method
The above code can be simplified into mydel d1 = M1;

Note: The delegate is a reference type, can be null, and if the delegate variable is null, an exception is thrown if called: NullReferenceException;

7,func, Action

. NET contains two generic delegate Func and action (under the mscorlib system of the Object Browser), the custom delegate type is basically not used in daily development

Func is a delegate with a return value, and the action is a delegate with no return value

8, anonymous method

There are many times when using delegate, it is not necessary to use an ordinary method, because this method is only used by this delegate, and only once, this time using the anonymous method is the most appropriate

Anonymous methods are methods that don't have names.

Example code:
MyDelegate p = delegate (int s) {s = 10;};

9,lambad-expression
Functional programming, a lot of the EntityFramework programming

1,action<int> a1 = delegate (int i) {console.write (i);};

2, can be simplified to:
action<int> A2 = (int i) =>{console.write (i);};/ /(= = read as goes to)

3, the parameter type can also be omitted (the compiler will automatically infer from the delegate type)
action<int> a3 = (i) =>{console.write (i);};

4, if only one parameter can also omit the parentheses of the argument (not many parameters)
action<int> a4 = i=>{console.write (i);};

5, if the delegate has a return value, and the method body has only one line of code, this line of code or return value, so long can even the method of curly braces and return are omitted

The original:func<int,int,string> f1 = delegate (int I,int j) {return "result is" + (i+j);};

Simplified to:func<int,int,string> f2 = (i,j) + "result is" + (I+J);

Common anonymous types are the same with lambda expressions

6, commissioned in-depth

Collection Common extension methods:

Where (Support delegate), Select (support delegate), Max, Min, ORDER by

First (Gets the number one, if not the exception)

FirstOrDefault (Gets the first one, if none of them returns the default value)

Single (Gets the only one, if there are no or more exceptions)

Singleordefault (Gets the only one, if not, returns the default value, more than one exception)

ToList, ToArray

7, the combination of delegates

The delegate object can be "+ added", and the new delegate object that is called after the combination invokes the combined fetch of the delegate: Mydel m5 = m1+m2+m3;

A combined delegate must be of the same delegate type

The "-" of a delegate is removed from the combined delegate;

If a delegate has a return value, there are some special ones. The combination of delegates is usually used for events, and is seldom used with ordinary delegates.

8, Event

Events Syntax: Event MyDelegate md1;

Added the event keyword to achieve the benefit of the mechanism: The event event is used, you can not modify the value of events registered, you can not impersonate the event notification. Only + =,-=

9, delegate and event summary

The role of the delegate:
placeholder, you can use a delegate variable instead of the method call (the return value of the delegate, and the argument list to be clear) when you do not know the specific code of the method to be executed in the future.
You need to assign a value to a delegate before it is actually called, otherwise null

The role of the event:
An event acts as a delegate variable, but is functionally more restrictive than a delegate variable.
Like what:
1, method (event handler) can only be bound by + = or-=
2, can only invoke (trigger) events inside the class

(interview) event and delegate relationship: The event consists of a private delegate variable and a add_*** and remove_*** method

Non-simplified notation for events: declaring a private delegate variable and the Add, remove method

10, differences and relationships between delegates and events

Wrong saying "event is a special kind of delegate"

The delegate uses more, the event only when develops WinForm, WPF uses only then more

Events, indexers, and properties are essentially methods.

What can I define in an interface?

Only methods can be defined in the interface. Interfaces can define "events, indexers, attributes," because they are also essentially methods.

13. Reflection

1, the role of reflection: Dynamic creation of objects, dynamic assignment, dynamic invocation method

2, Introduction to Reflection

1,. NET classes are compiled into IL, reflection can get information about the class at run time (what methods, fields, constructors, what the parent class is, etc.),
You can also create objects dynamically, invoke members

2, each class corresponds to a type object, each method corresponds to a MethodInfo object, and each property corresponds to a propertyinfo ....
These are the "metadata" of classes, methods, and properties (meta data).
Objects are not directly related to objects of this class.
These "metadata objects" are related to the members, regardless of the object, that is, each member corresponds to an object.

3, class meta-data type

1, use the written person class
1, get the Class Information object type method:
Get from object: Type type = Person.gettype ();
Gets from the class name: Type type =typeof (person); (type is a keyword, not a method)
Get from the full class name (namespace + class name): Type type = Type.GetType ("Com.rupeng.Person");

2, why do you have so many ways to get there?
The method is different, depending on the content to be queried.
If there is an object, use GetType ().
If there is no object can be used typeof;
Use Type.GetType ("Com.rupeng.Person") if you want to run the string to get through the configuration file, etc.

3,activator.createinstance (Type)
Create an object of this class using a parameterless construction method (if no argument constructor will report an exception).
The requirement class must have a parameterless constructor. Does the equivalent of new person () be idle egg ache?
2, what is returned by GetType () in the parent class? This represents "current object", not "current class"

Member Methods for 3,type

1,isinterface, IsArray, isprimitive, Isenum: Whether interfaces, arrays, primitive types, enumerations, and so on.

2,string name gets the class name (does not contain a namespace); String fullname contains the namespace

3,basetype gets the type of the parent class.

Members of the 4,type
1, constructor
ConstructorInfo GetConstructor (type[] types)//Get constructor for parameter type matching
Constructorinfo[] GetConstructors ()//Get all public constructors, including the parent class's
Call the object Invoke (object[] parameters) to call the constructor

2, Method
MethodInfo GetMethod (string name, type[] types)
methodinfo[] GetMethods ()//Get all public methods call to object Invoke (Object obj, object[] parameters) can call the method

3, the property
PropertyInfo GetProperty (String na Me) Gets a property
Propertyinfo[] GetProperties () Gets the primary member of all properties
PropertyInfo:
CanRead, CanWrite is read and write; Ge TValue, SetValue Read and write values (the first argument is which object to invoke)

4, commonly used attribute (features)
[Obsolete] Table name This member is obsolete

Properties can be modified when PropertyGrid is used
[ReadOnly (True)] is read-only in the editor and the code assignment is not affected;
[DisplayName ("name")] the display name of the property;
[Browsable (False)] property is visible

1,attribute syntax
attribute is used to append some meta-information to the code, which can be compiled by the compiler. NETFramework, or our program is used.
Attribute can be annotated on methods, properties, and classes

Generally play the role of description, configuration, naming generally end with attribute, if the end of attribute words can be omitted when used attribute

Annotations do not directly affect the actual logic of the code, only the auxiliary role, if the role is also the compiler,. NETFramework, procedures to parse the

You can call object[] GetCustomAttributes (type attributetype,bool inherit) on the type, MethodInfo, PropertyInfo, etc. to get the annotated object for the callout
Because the same attribute may be labeled multiple times, the return value is an array


14. Regular Expressions

1, a regular expression is a syntax that matches a string to determine whether a string conforms to a rule

2, basic meta-character:

A. Represents any single character other than \ n

B,[0-9] represents any number of integers between 0-9; [A-z] any lowercase letter; [A-z] any uppercase letter

c,\d for numbers, \d for non-numbers, \s for blanks, \s for non-whitespace, \w for lowercase letters or numbers and kanji
\w denotes special symbols

D,\ says for. and other special characters escaping

E, () promotion priority and extraction Group

F,[] represents any one of a range: [abc\d] represents either the ABC or any character in a number

g,| Representative or

H,+ is 1 times or unlimited

i,* is 0 times or unlimited

J? is 0 or 1 times.

K,{5} appears 5 times, {Two} appears once or twice, {5,8} appears 5 times to 8 times,

{1,} appears at least 1 times, {3,} appears at least 3 times
l,^ to. To begin with; End

Use Regex.IsMatch ("target string", @ "regular expression");//return value is bool type

Extract://Use () to group, and then call match. Groups[0]. Value is taken
Match match = Regex.match ("2016-12-29", @ "^ (\d{4}) \-(\d{1,2}) \-(\d{1,2})");

Example code:

Console.WriteLine (Regex.IsMatch ("2016-12-29", @ "^\d{4}\-\d{1,2}\-\d{1,2}$"));

Match match = Regex.match ("2016-12-29", @ "^ (\d{4}) \-(\d{1,2}) \-(\d{1,2})");
if (match. Success)
{
String year = match. Groups[0]. Value;
String month = match. GROUPS[1]. Value;
String day = match. GROUPS[2]. Value;
Console.WriteLine ("Year" +year+ "month" +month+ "Day" +day);
}
Else
{
Console.WriteLine ("Match unsuccessful");
}
Console.readkey ();

XV, serialization of objects

Object serialization is the conversion of an object into binary data (a byte stream), which is reverted to an object.

Use, avoid the program restarts and other circumstances caused by the loss of data, not only the program restart, the operating system restart will cause the disappearance of objects, even the Exit function range, etc. may cause the disappearance of the object

Serialization and deserialization are meant to preserve the persistence of objects

Note: An object that wants to be serialized must be labeled [Serializable] and its parent class and related fields and properties are labeled as "serializable"

Serialization only serializes fields in a class (only some state information is serialized)

Once the class structure changes, the contents of the previous serialization are not used as much as possible, otherwise it may go wrong!

Use:
There are two methods of the BinaryFormatter class:
void Serialize (Stream stream, object PBJ)

Object obj serialized into stream
Object Deserialize (Stream stream)
Deserializes an object from a stream, returning an object with a deserialized value

Why to serialize:
Preserve the persistence of objects, transform a complex object into streams, and facilitate our storage and information exchange

Application:
An out-of-process session in ASP. Object Serializable required
As well as XML serialization, JSON serialization in application development has replaced binary serialization and XML serialization.


16. XML (Extensible Markup Language)

1,xml Advantages:
easy to read; Format standard any language has a built-in XML analysis engine that does not have to be written separately for the file analysis engine

2, is a formatted way to store data, can be opened with Notepad, browser

3,. NET programs, App. config, Web. config files are XML files

4, Syntax specification:
tags/nodes (tag/node), nesting (Nest), properties. tags to be closed, attribute values to be surrounded by "", labels can be nested with each other

XML tree, parent node, child node, sibling node (siblings)

After the XML is written, it can be viewed with a browser, if it is wrong, the browser will prompt. If it is correct, the browser is still prompt error, it may be a file encoding problem.

5, Grammatical features:
Strictly case-sensitive;

There is only one root node

There must be an end tag for the start tag, unless it is self-closing and (when there is no content) <Person/>

property must use double quotation marks
(Can write not write, write the file type should pay attention to the actual saved file type need to be consistent)

Document declaration:
<?xml version= "1.0" encodeing= "Utf-8"?>

Comments:

<!--what to annotate--


6, note the coding problem, the actual code of the text file is consistent with the encoding in the document declaration

7. Read the XML file:
<Person>
<student stuid= "One" >
<StuName> Zhang San </StuName>
</Student>
<student stuid= ">"
<StuName> John Doe </StuName>
</Student>
</Person>


XmlDocument doc = new XmlDocument ();//Create a Reader object
Doc. Load (@ "path to XML file");//Load XML file
XmlNodeList students = Doc. documentelement.childnodes;//get the node collection for the XML file
foreach (XmlNode stu int students)
{
XmlElement element = (XmlElement) Stu;
String stuid = element. GetAttribute ("Stuid");
XmlNode NameNode = element. selectSingleNode ("Stuname");//Get the name of the person wiring
String name = Namenode.innertext;
Console.WriteLine (stuid+ "," +name);
}

8, generating an XML file

XmlDocument doc = new XmlDocument ();//Create an XML file object
XmlElement epersons = doc. CreateElement ("Persons");//Create root Node object
Doc. AppendChild (epersons);//Add the root node object to the XML file object
foreach (person person in epersons)
{
XmlElement Eperson = doc. createelement ("person");
Eperson.setattribute ("id", person.id.ToString ());
XmlElement ename = doc. CreateElement ("Name");
Ename.innertext = person. Name;
XmlElement eage = doc. CreateElement ("Age");
Eage.innertext = person. Age.tostring ();

Eperson.appendchild (ename);//Add child nodes to Eperson ename
Eperson.appendchild (eage);//Add child nodes to Eperson eage
Epersons.appendchild (Eperson);//Add Eperson to the root node
}
Doc. Save ("File full path");



Class Person
{
public person (int ID, string name, Int. age)
{
This. id = ID;
This. name = name;
This. Age = age;
}
public int Id {set; get;}
public string Name {set; get;}
public int Age {set; get;}
}

person[] persons = {New person (1, "Rupeng", 8), new person (2, "Baidu", 6)};

such as Peng Web study notes (three). NET Advanced Technology

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.