English 中文(简体)
如何将<衍生的地图>分配给计算数字的“基本地图”参数?
原标题:How can List<DerivedClass> be assigned to IEnumerable<BaseClass> parameter?
  • 时间:2012-01-12 21:38:48
  •  标签:
  • c#
  • list

我的理解是,清单和编号;衍生类别不能直接分配给清单和编号;不能直接分配给基类。 但是,它如何允许将同一清单加附和;加固;衍生类别分配到一个可计算、可计算、可计算、可计算、且可计算;基类参数类型。

public class Base 
{}

public class Derived : Base 
{}

public class Test
{
   // inside some method...
   List<Derived> someElements;
   ReadElements(someElements);

   public void ReadElements(List<Base> elements) // this throws compile error
   {...} 

   public void ReadElements(IEnumerable<Base> elements) // this one works
   {...}
}

I know that the List is an implementation of IEnumerable and support indexing and modifying elements, but I don t seem to understand this part? Can someone please explain? Thanks.

最佳回答
问题回答

<代码>IList 和List 没有将其代码<>T<>/code>定义为out>>,而IEvidable则未作界定。 <代码>List为一类,因此可以tout,IList 不定义<>out>>。 因为它接受“<代码”类型的投入。 T

仅从<条码><<>>> > > > 代码<> 可计数<>/代码> 取而代之,但因<条码>,可在上加至<条码>。 缩略语 (事实上,它必须参看@ChrisShain关于夫妻关系和违反婚姻关系的答案)。

考虑这一法律本身是完全合法的:

public void AddElements(List<Base> elements)
{
    Base item = new Base();
    elements.Add(item);
}

但是,如果你称之为:

List<Derived> elements = new List<Derived>;
AddElements(elements);

类别<代码>Base不继承Derived,因此不能列入elements。 因此,这是一个潜在的问题,因而是非法的。

On the other hand, IEnumerable<Base> only provides methods to read the collection, not write to it, so the above contradiction cannot occur.





相关问题
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. ...

热门标签