获取匿名类型的Intellisence

来自于:AlexJ
http://blogs.msdn.com/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx
T CastByExample<T>(object o, T example)

So earlier today I was lamenting that an anonymous type can't be shared between functions with Wes Dyer, when he said "Well actually they can..."

Cue me learning something cool.

The first step is to create a seemingly innocent method:

public static T CastByExample<T>(this object o, T example)
{
    return (T) o;
}

Seems innocent enough right?

 

Well it is until you start using it with anonymous types. Imagine you had this function, that returns an anonymous type as object, because that is your only choice:

static object GetAnonymousType()
{
    return new { FullName = "Cosmo Kramer" };
}

Normally if you called this function anywhere you wouldn't be able to get at the anonymous type without using reflection... This is where CastByExample<T> comes to the rescue.

 

If you know the shape of the anonymous type, you use that to do a CastByExample...

object o = GetAnonymousType();

//get the original anonymous type back again
var v = o.CastByExample(new { FullName = "" });

 

//Use the properties of the anonymous type initialized in another
//function directly !!
Console.WriteLine(v.FullName);

This works because when an anonymous type is used the compiler first checks that one with the same signature (i.e. all fields are the same name and type) hasn't already been used. If one has the same CLR type is used.

Hence if you pass in an example that is the same shape as the original anonymous type to the CastByExample<T>(..) method will get you back to the original anonymous type... and var magic does the rest.

Nifty huh?

 

 

来自于:AlexJ
http://blogs.msdn.com/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx

 

posted @   laughter  阅读(206)  评论(0)    收藏  举报
编辑推荐:
· 记一次 .NET某固高运动卡测试 卡慢分析
· 微服务架构学习与思考:微服务拆分的原则
· 记一次 .NET某云HIS系统 CPU爆高分析
· 如果单表数据量大,只能考虑分库分表吗?
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
阅读排行:
· 7 个最近很火的开源项目「GitHub 热点速览」
· DeepSeekV3:写代码很强了
· 博客园2025新款「AI繁忙」系列T恤上架
· 记一次 .NET某固高运动卡测试 卡慢分析
· Visual Studio 2022 v17.13新版发布:强化稳定性和安全,助力 .NET 开发提
点击右上角即可分享
微信分享提示