栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

转换为匿名类型

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

转换为匿名类型

注意
,根据注释,我只想指出,当您需要像这样在程序中传递实类型时,我也建议使用实类型。匿名类型实际上应该一次只在一种方法中本地使用(我认为),但是无论如何,这就是我剩下的答案。


您可以使用技巧,通过诱使编译器为您推断正确的类型:

using System;namespace ConsoleApplication4{    class Program    {        static void Main(string[] args)        { var a = new { Id = 1, Name = "Bob" }; TestMethod(a); Console.Out.WriteLine("Press enter to exit..."); Console.In.ReadLine();        }        private static void TestMethod(Object x)        { // This is a dummy value, just to get 'a' to be of the right type var a = new { Id = 0, Name = "" }; a = Cast(a, x); Console.Out.WriteLine(a.Id + ": " + a.Name);        }        private static T Cast<T>(T typeHolder, Object x)        { // typeHolder above is just for compiler magic // to infer the type to cast x to return (T)x;        }    }}

诀窍在于,在程序集中,相同的匿名类型(相同的属性,相同的顺序)解析为相同的类型,从而使上述技巧起作用。

private static T CastTo<T>(this Object value, T targetType){    // targetType above is just for compiler magic    // to infer the type to cast value to    return (T)value;}

用法:

var value = x.CastTo(a);

但是,我们实际上是在推动极限。使用实型字体,外观和感觉也会更干净。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576202.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号