问题描述
我仍然在学习一些这个c#的东西,我找不到这个问题的答案。假设我有一个MyObject实现MyInterface的列表
I'm still learning some of this c# stuff, and I couldn't find an answer to this question. Assuming that I have a list of MyObject implementing MyInterface
public class MyObject : IMyInterface { ...}
public List<MyObject> MyObjectList;
如何返回 IEnumerable< IMyInterface>
与MyObjectList的内容?
How can I return an IEnumerable<IMyInterface>
with the contents of MyObjectList?
我的意思是,现在我有这个:
I mean, right now I have this:
List<IMyInterface> temp = new List<IMyInterface>();
foreach (MyObject obj in MyObjects) temp.Add(obj);
return (IEnumerable<IMyInterface>)temp;
但是是否需要创建一个这样的新列表?
But is it necessary to create a new list like this?
谢谢。
推荐答案
如果使用.NET 3.5,最简单的方法是:
If you're using .NET 3.5, the easiest way to do this is:
return MyObjects.Cast<IMyInterface>();
你不需要创建一切的副本 - 但直到C#4出来的通用
You don't need to create a copy of everything - but until C# 4 comes out with its generic interface variance, you're stuck doing something like this.
如果你还在使用.NET 2.0,你可以很容易做类似的事情:
If you're still using .NET 2.0, you can easily do something similar:
public static IEnumerable<TResult> SafeCast<TSource, TResult>
(IEnumerable<TSource> source) where TResult : TSource
{
foreach (TSource item in source)
{
yield return item;
}
}
(请注意,这不会检查 source
为null;要正确地做,你会想要两个方法,由于延迟执行迭代器块。)
(Note that this doesn't check for source
being null; to do that properly you'd want two methods due to the deferred execution of iterator blocks.)
然后使用:
return SafeCast<MyObject, IMyInterface>(MyObjects);
您可以使其更像LINQ版本, / p>
You could make it more like the LINQ version, like this:
public static IEnumerable<T> SafeCast<T>(IEnumerable source)
{
foreach (T item in source)
{
yield return item;
}
}
return SafeCast<IMyInterface>(MyObjects);
这有编译时的安全性 - 它不会阻止你尝试转换例如
This has compile-time safety though - it wouldn't stop you from trying to convert a List<string>
into an IEnumerable<Guid>
for example.
这篇关于铸造列表< MyObject>到IEnumerable< MyInterface>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!