为了对方法进行“后处理”,我想将一个额外的函数导入到方法中。
如何导入返回匿名类型作为 .Select 扩展方法参数的 Func
?
表达式是匿名的,例如:
p => new
{
ThumnailUrl = p.PicasaEntry.Media.Thumbnails[0].Attributes["url"],
ImageUrl = p.PhotoUri
}
并且需要在参数??????并在 .Select(?????) 处执行
private void BindControl<T, U>(string uri, DataBoundControl target, ?????)
where T : KindQuery, new()
where U : PicasaEntity, new()
{
PicasaFeed feed = CreateFeed<T>(uri);
albumList.DataSource = GetPicasaEntries<U>(feed).Select(?????);
albumList.DataBind();
}
更新:
最后我想这样调用它:
string albumUri = PicasaQuery.CreatePicasaUri(PicasaUserID, PicasaAlbumID);
BindControls<AlbumQuery, Album>(albumUri, albumList, ?????);
string photoUri = PicasaQuery.CreatePicasaUri(PicasaUserID, PicasaAlbumID);
BindControls<PhotoQuery, Photo>(photoUri, slideShow, ?????);
其他方法如下:
private PicasaFeed CreateFeed<T>(string uri)
where T : KindQuery, new()
{
PicasaFeed feed = null;
try
{
PicasaService service = new PicasaService(PicasaApplicationName);
T query = new T();
query.BaseAddress = uri;
feed = service.Query(query);
}
catch (Exception ex)
{
//exception handling not shown
}
return feed;
}
private IEnumerable<T> GetPicasaEntries<T>(PicasaFeed feed)
where T : PicasaEntity, new()
{
if(feed == null){
return null;
}
IEnumerable<T> entries = null;
string cacheKey = feed.Id.ToString();
if(Cache.Get(cacheKey) == null)
{
entries = feed.Entries.Select(x => new T() { AtomEntry = x }).ToList();
Cache.Insert(cacheKey, entries,
null, Cache.NoAbsoluteExpiration, new TimeSpan(0,20,0));
}
return entries;
}
最佳答案
匿名类型实际上只为本地使用而设计。在强类型语言中,不能被强类型化的类型并不真正被鼓励用于一般用途……它们只是动态世界中 c# 小舞的一部分。
你有两个选择。
创建强类型。
class Entry
{
public string ThumnailUrl { get; set; }
public string ImageUrl { get; set; }
}
然后使用:
p => new Entry
{
ThumnailUrl = p.PicasaEntry.Media.Thumbnails[0].Attributes["url"],
ImageUrl = p.PhotoUri
}
或者称它为Object。然后使用反射来获取数据 - 我不推荐这样做。
关于c# - 从 Func<T> 返回匿名作为 .Select() 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5880748/