"C # Review Summary" Anonymous type origin

Source: Internet
Author: User
Tags throw exception

1 Properties

this has to start with the property, why it is not more convenient for external code to access the data inside the object using attributes rather than direct access, but it turns out that direct access is unsafe. So,Anders Hejlsberg(Anders Heilsberg) added attributes to C # This syntax sugar, used as a data member, but actually setxx () and getxx (), both safe and convenient.

Properties: is the preferred way to access objects because they prohibit external code from accessing the implementation of the data storage mechanism inside the object.

 Public int myintprop{    get    {    //propertyGet code    }     Set    {    //proerty Set code    }}    

1.1 Get keyword

a Get block must have a return value for a property, and a simple property is generally associated with a private field to control access to the field, at which point the get block can return the value of the field directly, for example:

Private int myInt;  Public int  myintprop{  get  {  return  myInt; }  set  {  //propertyset code. }}

The code outside of the class cannot directly access the MyInt field, which is private and must be accessed using the property.

1.2 Set keyword

The Set function assigns a value to a field in a similar way. Here , value is used to represent the property values provided by the user:

Private int myInt;  Public int  myintprop{  get  {  return  myInt;  }  Set= value; }}

Value equals the same value as the property, so if the property and field use the same type, you don't have to worry about data type conversions.

This simple property only accesses the MYINT field directly. With more control over the operation, the real effect of the attribute can be played out, for example, using the following code to implement the set block:

Set {  if0= value;}

only the value assigned to the property is between 1~10 and MyInt is changed . At this point, make an important design choice: What to do if an invalid value is used:

    • I don't do anything.
    • Assigning a default value to a field
    • Continue execution as if no error occurred, but record the event for future analysis
    • Throw exception

In general, the next two choices work better, which option depends on how the class is used and how much control is granted to the user. Throwing exceptions gives the user quite a lot of control, such as:

Set  {  if0= value;  Elsethrow (new ArgumentOutOfRangeException ("myintprop  ", Value,"Myintprop must be assigned a value between 0 and ten. " ))}    

this can be handled by try...catch...finaly logic in the code that uses the property .

Note: Attributes can use the virtual,override , and abstract keywords, just like methods, but these keywords cannot be used for fields. Finally, as mentioned above, accessors can have their own accessibility.

Instance:

 Public classmyclass{ Public ReadOnly stringName;Private intintval; Public intval{Get{returnintval; }Set{if(Value >=0&& value <=Ten) Intval=value; Else        Throw(NewArgumentOutOfRangeException ("Val", Value,"Val must be assigned a value between 0 ang.")); }} Public Override stringToString () {return "Name:"+name+"\nval:"+Val;}PrivateMyClass (): This("Default Name"){} PublicMyClass (stringnewName) {Name=NewName; Intval=0;}}Static voidMain (string[] args) {Console.WriteLine ("Creating Object MyObj ..."); MyClass MYOBJ=NewMyClass ("My Object"); Console.WriteLine ("MYOBJ created.");  for(inti =-1; I <=0; i++) {Try{Console.WriteLine ("\nattempting to assign {0} to Myobj.val ...", i); Myobj.val=i; Console.WriteLine ("Value {0} assigned to Myobj.val.", Myobj.val); }Catch(Exception e) {Console.WriteLine ("Exception {0} throw.", E.gettype ().      FullName); Console.WriteLine ("message:\n\ "{0}\"", E.message); }} Console.WriteLine ("\noutputting myobj.tostring () ...");  Console.WriteLine (Myobj.tostring ()); Console.WriteLine ("myobj.tostring () Output."); Console.readkey ();}

The code in Main () creates and uses an instance of the MyClass class that is defined in MyClass.cs . Instantiating this class must be done using a non-default constructor, because The default constructor for the MyClass class is private.

Main ()try to giveMYOBJ(MyClassinstance) of theValThe property is assigned a value. forloops are assigned in two times-1and the0,Try: Catch ...The structure is used to detect thrown exceptions. Put-1when assigned to a property, it throws asystem.argumentoutofexceptiontype of exception,Catchthe code in the block outputs the abnormal information to the console window. In the next loop, the value0the successful assignment to theValproperty to assign the value to the private field by this propertyintval.

2 Automatic Properties

However, Anders still feels that the code is too much, and should be optimized, to come up with automatic attributes.

automatic attributes. With automatic attributes, you can declare properties with simplified syntax, and the C # compiler automatically adds what you don't type, specifically, the compiler declares a private field for storing properties, and the property's get and Set the field in the block (very intimate), we do not need to consider the details.

 Public int  myintprop{  get;  set;}

we define the accessibility, type, and name of the property in the usual way. However, there is no code that provides implementations for get and set blocks. The implementation code for these blocks (and the underlying fields) is provided by the compiler.

when using automatic attributes, data can only be accessed through properties and cannot be accessed through the underlying private fields, and we do not know the name of the underlying private field (the name is defined during compilation). This is not a real limitation, however, because the property name can be used directly. The only limitation of automatic attributes is that they must contain get and set memory, which cannot be used to define read-only and write-only properties.

3 Object initializer

Object initializer definition: The initializer is divided into an object initializer and a collection initializer, where we are talking about an object initializer,

Function: Creates a new object with less code and assigns values to several properties and public data members of the object.

When it comes to initializers, let's talk about constructors, constructs from the surface meaning to know that this is used to build the class (of course, the initialization of some members is also within the scope of the build, but there are other functions)

Object initialization: Define the properties of the class first, and then instantiate and initialize the class.

defining the properties of a class is defined by an automatic attribute, and instantiating and initializing an object instance of this class must be The default parameterless constructor inside C # implements the next snippet of code.

Let's look at a class definition:

 Public class curry{    publicstringgetset;}      Public string Get Set ; }      Public int Get Set ; }}

This class has 3 attributes, which are defined by the automatic attribute syntax. If you want to instantiate and initialize an object instance of this class, you must execute several statements :

    1. The first way
New"panir Tikka" "jalfrezi"   8;

if a constructor is not included in the class definition, this code uses the the default parameterless constructor provided by the C # compiler. It's still a bit complicated, and it should be simpler than that, you guessed it.

2. Second way (remove brackets)

Curry tastycurry=New  curry{    "panir Tikka",    "  jalfrezi",    8,}

and then the question is, if you have a data member, how many instances of an object instance of this class are instantiated and initialized? To simplify this process, Anders is a little bit smarter. Think of a more advanced way to adopt a suitable non-default constructor.

As follows:

Class Tastycurry =new Curry ("Panir Tikka", "Jalfrezi",8);

This code works very well and it enforces the use of The code for the Curry class uses this constructor, which prevents code that previously used the parameterless constructor from running.

4 Anonymous Types

Do you think this is very convenient, can only say that you are too young, heavens beyond heavens, someone outside, look at our topic, yes, it is, our protagonist, anonymous type.

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. the type name is generated by the compiler and cannot be used at the source code level. The type of each property is inferred by the compiler. You can create an anonymous type by using the new operator and the object's initial value.

Here, let's raise a chestnut.

The following example shows the use of two names as a The Amount and Message properties are initialized with the anonymous type.

var New {mainingredient = "Panir Tikka", Style = "Jalfrezi" spiciness=8};   + v.style+v.spiciness);  

See, right, yes, it's that simple.

Remarks: About Why should the anonymous type of C # Restrict properties to read-only?

I think it's good to say something from a netizen.

In fact, the anonymous type is C # 3.0 introduced all the new features introduced inC # 3.0 to implement the great language features of LINQ. Anonymous types are used to solve the problem of selecting part of a field in LINQ and multiple fields as grouped by aggregation or multi-field joins. So, to be blunt, the goal of anonymous type design is tuples. An anonymous type is essentially a mapping of tuples in a relational model in C # . Tuples are obviously immutable, and anonymous types do not have to be designed to be mutable for trouble.

At this point, the origin of the anonymous type is generally clear, mainly because engineers want to easily optimize the code, creative creation, the anonymous type was born.

References: "C # Getting Started Classic fifth Edition" "Know"

Friendly Tips Mhq_martin Blog Park address:http://www.cnblogs.com/mhq-martin/This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

C # Review Summary Anonymous type Origin

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.