Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
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
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.
Foo<object>
Thanks
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?
您可以拥有一个添加了子类的基本类型的集合。例如,以下将起作用:
// 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...
使用 List(T) 或 Array 的 ConvertAll 方法。
http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx
是的,在 C# 4.0 中是可能的!
你应该研究covariance。
有关的:
C# 4.0 中如何实现泛型协方差和逆变换?