English 中文(简体)
C# 协变问题
原标题:C# Covariance issue

我有一个由Linq-to-SQL生成的领域实体,我将其强制转换为正确的接口,如下所示:

public IEnumerable<IApplication> GetApplications()
    {
        using (var dc = new LqDev202DataContext())
        {
            return dc.ZApplications.Cast<IApplication>().ToList();
        }
    }

但是,我重新命名了linq-to-sql表,而没有触及我的部分类,并且代码仍然被编译。

该列表具有正确数量的元素,但它们都是空的。

我需要编写一个帮助方法来确保这将起作用,还是有一个编译时安全的简单内置方法可以在.net 3.5中完成这项工作?

最佳回答

如果需要,您也可以使用此功能进行转换的投射:

public static IEnumerable<TDest> CastAll<TItem, TDest>(this IEnumerable<TItem> items)
{
 var p = Expression.Parameter(typeof(TItem), "i");
 var c = Expression.Convert(p, typeof(TDest));
 var ex = Expression.Lambda<Func<TItem, TDest>>(c, p).Compile();

 foreach (var item in items)
 {
    yield return ex(item);
 }
}

http://adventuresdotnet.blogspot.com/2010/06/better-more-type-safe-alternative-to.html

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签