C#技巧:Cast By Example(如何将弱类型的匿名类型参数转换为强类型)
[csharp]using System;
namespace ConsoleApplication1
{
class Program
{
static T CastByExample<T>(object obj, Func<T> example)
{
return (T)obj; www.zzzyk.com
}
static void f(object p)
{
var person = CastByExample(p, () => new { Name = "", Age = 0 });
Console.WriteLine("Name={0},Age={1}", person.Name, person.Age);
}
static void Main(string[] args)
{
var person = new { Name = "Tom", Age = 25 };
f(person);
}
}
}
//Name=Tom,Age=25
作者:zwvista
补充:软件开发 , C# ,