当前位置:编程学习 > C#/ASP.NET >>

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# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,