我想创建一个源自ToDictionary(). 目前为了达到预期的结果,我这样做:
ObjectAttributes = model.ObjectAttributes.ToDictionary(
oa => oa.Attribute.Name, oa => oa.ToWrapper<ObjectAttributeWrapper>());
所以我使用以下ToDictionary签名:
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector);
我想知道是否可以这样做?
ObjectAttributes = model.ObjectAttributes.ToDictionaryWrapper<ObjectAttributeWrapper>(
oa => oa.Attribute.Name);
这是当前的实现,但显然不起作用:
public static Dictionary<TKey, TWrapper> ToDictionaryWrapper<TWrapper, TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) where TSource : BaseModel where TWrapper : IBaseWrapper
{
return source.ToDictionary(keySelector, model => model.ToWrapper<TWrapper>());
}
编辑:实施ToWrapper():
public static TWrapper ToWrapper<TWrapper>(this BaseModel model) where TWrapper : IBaseWrapper
{
if (model == null)
return default;
var type = typeof(TWrapper);
if (_wrapperParents.ContainsKey(type) && _wrapperParents[type].Id == model.Id)
return (TWrapper)_wrapperParents[type];
else
return (TWrapper)GetConstructor<TWrapper>().Invoke(new object[] { model });
}
public static IEnumerable<TWrapper> ToListWrapper<TWrapper>(this IEnumerable models) where TWrapper : IBaseWrapper
{
var _models = models as IEnumerable<BaseModel>;
if (_models == null)
return default;
return _models.Select(model => model.ToWrapper<TWrapper>());
}
呼如林
相关分类