Use of attribute PropertyInfo in C #

Source: Internet
Author: User

Yesterday programming encountered a problem two class fields are more than 20, of which there are more than 10 are the same, you need to assign a class field to another class, the beginning of their own want to manually one by one to assign values, and then think of C # basic knowledge, with PropertyInfo can solve similar problems, Blog Park to write a blog needs to be detailed, I still slowly C # properties from scratch, first look at the definition of the property:

Property Definition: It provides a flexible mechanism to read, write, or calculate the value of a private field. You can use properties as you would with public data members, but in fact they are special methods called accessors. This makes it easy to access data, and also helps to improve the security and flexibility of the method. Properties can often be divided into general and automatic properties. There is a little difference between the two, at the beginning of programming to two completely no concept.

General properties

General properties are often used when doing WinForm, and now starting with EF, basically using automatic attributes to see the complete composition of the general properties:

1. Private fields, which are generally set to private, are guaranteed to be secure by assigning values through attributes:

1

private string _age;

The 2.get accessor, which is responsible for reading the data, can perform its own logical judgment and data validation, ending with a return or throw:

1

2

3

4

5

Get

{

Judgment of the age return value

Return _age> 0? _age:0;

}

The 3.set accessor, which assigns a value to a property, resembles a method with a return type of void, and can contain logical processing, such as the ability to return a result based on the default value.

Automatic properties

It's a simple one. General properties, you can use automatic properties when no other logic is required in the property accessor, but one thing to note is that when declaring an automatic property, the compiler creates a private, anonymous fallback field that can be accessed only through the property's get and set accessors.

1

public int Id {get; set;}

Automatic attributes there's not much to say, just a simple comparison between the general and automatic attributes:

1. Auto-implemented properties must declare both get and set accessors. When you create a readonly auto-implementation property, you need to set the set accessor to private.

2 attributes can be used on auto-implemented properties and cannot be used on supported fallback fields. If attributes are used on the backing field of a property, only general properties should be created.
3. Automatic implementation of Property Get, and set cannot contain special logical processing. Similar to fields, but different from fields. Unlike fields, properties are not categorized as variables, and properties cannot be passed as ref parameters or out parameters.

Use of property PropertyInfo

The difference between a property and an automatic attribute is probably simply described above, and it is now possible to revert to the problem at the very beginning of the article:

1. Case 1, if most of the two classes have the same field, you need to assign a field of one of the classes to another class:

Define the Person class:

1

2

3

4

5

6

7

8

9

10

11

public class person {

        public person (int id,string name,string address)

        {

            this. id = ID;

           this. name = name;

           this. address = address;

       }

       public int id {get; set;}

       public string name {get; set;}

       public string address {get; set;}

   }

Defining the User Class

1

2

3

4

5

public class User {

public int Id {get; set;}

public string Name {get; set;}

public string Group {get; set;}

}

Conversion method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

public static user Convertobject (user User,person person)

{

propertyinfo[] Userpro = user. GetType (). GetProperties ();

propertyinfo[] Personpro = person. GetType (). GetProperties ();

if (userpro.length>0&&personpro.length>0)

{

for (int i = 0; i < userpro.length; i++)

{

for (int j = 0; J < Personpro.length; J + +)

{<br>//Determine if the user's property is in person

if (Userpro[i]. Name = = Personpro[j]. Name && Userpro[i]. PropertyType = = Personpro[j]. PropertyType)

{

Object Value=personpro[j]. GetValue (person, NULL);

Assigns the value of the property in person to User<br> Userpro[i]. SetValue (user,value, NULL);

}

}

}

}

return user;

}

Method is called:

1

2

3

4

5

P align= ' left ' >6

7

8

9

10

static void main (string[] args)

       {

          person person = new  Person (1, "Flyelephant", "Beijing");

          user User = New user ();

          user. Id =;

          user = convertobject (user, person);

          console.writeline ("Id:"  + user . Id + "Name:"  + user. Name + "role:"  + user. Group);

          system.console.read ();

&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}

&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;

2. I used to go back to SqlHelper when I was doing WinForm, and now there are many companies that use it, and many things feel like repetitive operations, Once thought that programming is just copy paste, the following code people should be very common:

1

2

3

4

5

6

7

8

9

10

list<person> list = new list<person> ();

SqlDataReader SDR = new SqlDataReader ();

while (SDR. Read ())

{

person person = new person ();

Person. Name = SDR. GetString (0);

//.... Similar to the following

List. ADD (person);

}

Start writing feel is exercise, write more feel bored, in fact, can completely change a way to achieve the above code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

public static list<t> convertdata<t> (SqlDataReader SDR)

{

list<t> list = new list<t> ();

Type type = typeof (T);

Propertyinfo[] Properties = type. GetProperties ();

while (SDR. Read ())

{

T model = activator.createinstance<t> ();

for (int i = 0; i < properties. Length; i++)

{

for (int j = 0; J < SDR. FieldCount; J + +)

{

Determine whether the name of the property is the same as the name of the field

if (Properties[i]. Name = = SDR. GetName (j))

{

Object value =sdr[j];

Assign the value of a field to a property in user

Properties[i]. SetValue (model, value, NULL);

}

}

}

List. ADD (model);

}

return list;

}

1

2

3

list<user> list = new list<user> ();

SqlDataReader SDR = cmd. ExecuteReader ();

List = convertdata<user> (SDR);

3. case Three, the Ajax page pass-through value can be converted using the Get method, or the post-mode transfer JSON format data

Simple conversion of a get pass string name=xx&age=xx, the background directly with a dictionary to simulate:

1

2

3

4

dictionary<string, object> dic = new dictionary<string, object> ();

Dic. ADD ("Id", 100);

Dic. ADD ("Name", "Keso");

Dic. ADD ("Group", "programmer");

Conversion Dictionary method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

public static T convertdic<t> (dictionary<string, object> dic)

{

T model = activator.createinstance<t> ();

propertyinfo[] Modelpro = model. GetType (). GetProperties ();

if (modelpro.length > 0 && dic. Count () > 0)

{

for (int i = 0; i < modelpro.length; i++)

{

if (DIC. ContainsKey (Modelpro[i]. Name))

{

Modelpro[i]. SetValue (model, Dic[modelpro[i]. Name], NULL);

}

}

}

return model;

}

The Last Call:

1

User user = convertdic<user> (DIC);

Use of attribute PropertyInfo in C # (GO)

Related Article

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.