8

does anyone know if it is possible to cast a generic type with a certain type parameter (e.g. Bar) to the same generic type with the type parameter being a base type of Bar (such as object in my case). And, if it is possible, how would it be done?

What I want to do is have a collection of Foo<object> but be able to add Foos with more specific type arguments.

Thanks


Are you sure that the control whose child controls you are parsing actually directly contains Label controls? I suspect that it is a child of the main control that is hosting the labels, in which case, you need to recursively search through the UI tree to find the labels.

Something like:

public static IEnumerable<Label> DescendantLabels(this Control control)
{
   return control.Controls.DescendantLabels();
}

public static IEnumerable<Label> DescendantLabels(this ControlCollection controls)
{
    var childControls = controls.OfType<Label>();

    foreach (Control control in controls)
    {
       childControls = childControls.Concat(control.DescendantLabels());
    }

    return childControls;
}
4

4 に答える 4

3

サブクラスが追加された基本タイプのコレクションを持つことができます。たとえば、次のように機能します。

// Using:
public class Foo {} // Base class
public class Bar : Foo {} // Subclass

// Code:
List<Foo> list = new List<Foo>();
HashSet<Foo> hash = new HashSet<Foo>();

list.Add(new Bar());
list.Add(new Foo());

hash.Add(new Bar());

「Bar」は「Foo」の特定のタイプであるため、Fooのコレクションに追加することは完全に合法です。

ただし、.NET 4と共分散のout修飾子が必要になるまで、次のことはできません。

IEnumerable<Foo> list = new List<Bar>(); // This isn't supported in .NET 3.5...
于 2010-04-07T17:01:10.623 に答える
2

List(T)またはArrayのConvertAllメソッドを使用します。

http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx

于 2010-04-07T16:58:11.750 に答える
2

はい、C#4.0で可能です!

共分散を調べる必要があります。

于 2010-04-07T17:00:15.663 に答える
0

関連している:

C# 4.0 ではジェネリック共分散と反分散はどのように実装されていますか?

于 2010-04-07T17:02:13.507 に答える