How to restrict a collection to store only specific types of objects?
I have a property in the class which is used as a reply type of the operation contract in WCf servi开发者_Go百科ce which communicates to the legacy ASMX clients.
[XmlArrayItem(Type = typeof(Person), Namespace = "TestNamespace")]
[XmlArrayItem(Type = typeof(Department),
Namespace = "TestNamespace")]
public Collection<object> OrgCollection { get; set; }
But if the consumer adds some other type than expected types, service crashes because XmlSerializer
fails to serialize this property.
Is there a way to have a collection of some specific types? Generics would be the answer to it but instead of implementing a new collection class altogether, can I "inherit" my new class from some existing collection class so that all the functionality would be available to me?
You could use a System.Collections.Generic.List for a collection of a specific type. You can also inherit from List to add your own functionality if you want to.
Look at the System.Collections.Generic namespace.
According to your comment "I want a "single" collection which is capable of storing objects of some specified types.":
Create some middle class A
:
class A<T1, T2> {}
and then use:
List<A<T1, T2>> OrgCollection { get;set }
or use the Tuple<T1, T2>
class (.NET 4.0).
精彩评论