c#3.0: Using the anonymous type passed out

Source: Internet
Author: User
Tags anonymous

Today I saw a video on csdn to explain c#3.0, although the speaker a bit stuttering but I still insist on listening to finish. There's a phrase in it that I'm interested in, and if it's structurally identical we can do a strong turn on an anonymous type. It seems that at the critical moment we can still directly manipulate the anonymous type although it's a bit of a hassle.

We know that an anonymous type is actually a generic class that is automatically generated by. NET and uses the same anonymous type as long as the field name is the same type. So as long as the class uses this feature, we can make a strong turn of an anonymous type passed by parameter.

public T CastAnonymous<T>(object anonymous, T anonymousType)
{
   return (T)anonymous;
}
class User
{
   public string Name { get; set; }
}
public static void Main()
{
   var u = new User{ Name = "Lucifer" };
   var a = new { a = 26; u.Name; b = false };
   Print(a);
}
public void Print(object anonymous)
{
   var a = CastAnonymous(anonymous, new { a=0, Name = "", b = false });
   Console.WriteLine{"{0} - {1} - {2}", a.a, a.Name, a.b};
}

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.