感谢http://blog.csdn.net/jjx0224/article/details/5887589
感谢http://hi.baidu.com/guodong828/blog/item/cc53404ef40af002b3de0500.html
c# 匿名类 上代码:
class="dp-c" style="font: 14px/26px Consolas, 'Courier New', Courier, mono, serif; margin: 0px 0px 1px 45px !important; padding: 0px; text-align: left; color: #5c5c5c; text-transform: none; text-indent: 0px; letter-spacing: normal; word-spacing: 0px; white-space: normal; font-size-adjust: none; font-stretch: normal; background-color: #e7e5dc; -webkit-text-stroke-width: 0px;">
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace ConsoleApplication1
- {
-
-
-
-
-
- class Program
- {
- static void Main(string[] args)
- {
- var a = new { name = "it小金", age = 24 };
-
- string b = a.name.ToString();
- int c = a.age;
- Console.WriteLine(b);
- Console.WriteLine(c);
- Console.Read();
- }
- }
- }
用到匿名类,难免碰到匿名类转换问题,上代码:
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, Name = 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};
}