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


Can I make a symfony sfValidatorFile required ONLY if the action is 'new'?

I have an admin form that lets users create entities that require an image. So in the form class, I have a sfValidatorFile object that sets the 'required' option to true. This is perfect behavior when the user creates a new entity. The problem arises when they edit an existing entity. They shouldn't have to select an image every time they edit the entity, but if they don't, symfony returns an error complaining that the image is required. So is it possible to make sfValidatorFile use the 'required' option conditionally?

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 中是可能的!

你应该研究covariance

于 2010-04-07T17:00:15.663 回答
0

有关的:

C# 4.0 中如何实现泛型协方差和逆变换?

于 2010-04-07T17:02:13.507 回答