C # dynamic type and Anonymous class,

Source: Internet
Author: User

C # dynamic type and Anonymous class,
A simple example of dynamic type

Dynamic expando = new System. Dynamic. ExpandoObject (); // readable and writable dynamic field
Expando. Id = 1;
Expando. Name = "Test ";
String json = Utils. ConvertJson. JsonEncode (expando); // output {Id: 1, Name: 'test '}

 

// Add fields dynamically

List <string> fieldList = new List <string> () {"Name", "Age", "Sex"}; // From config or db

Dynamic dobj = new System. Dynamic. ExpandoObject ();

Var dic = (IDictionary <string, object>) dobj;
Foreach (var fieldItem in fieldList)
{
Dic [fieldItem] = "set" + fieldItem + "value";/* implement the function of dynamically adding attributes similar to those in js

Var obj = {};
Var field = "Id ";

Eval ("obj." + field + "= 1 ");

Alert (obj. Id); // 1 */


}
Var val = dobj. Name; // "set Name value"

Var val1 = dobj. Age; // "set Age value"

Enumerate all members of this object

Foreach (var fieldItem in (IDictionary <String, Object>) dobj)
{
Var v = (fieldItem. Key + ":" + fieldItem. Value );
}

Anonymous class

// Var aaaa = new {Id = 1, Name = "Test"}; // The anonymous field is read-only and cannot be written.

Dynamic aaaa = new {Id = 1, Name = "Test"}; // The anonymous field is read-only and cannot be written.
Aaaa. Id = 2; // an error cannot be returned if it is not writable. The value cannot be assigned to the attribute or indexer "<> f _ AnonymousType1 <int>. Id"-it is read-only.

 

Dynamic obj = Newtonsoft. Json. JsonConvert. DeserializeObject ("{Name: 'A', Sex: 'male', Age: 11 }");
Var name = obj. Name. Value; // aa

 

Address: http://www.cnblogs.com/xuejianxiyang/p/4964739.html

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.