Collection of various types
In the current system I'm working on I need to have functionality for ammendments.
That being that a user can create an ammendment package and that package contains new version of various domain objects (not structure changes just data changes).
I want to have an "AmmendmentPackage" that contains all of the ammendments that are to be made to various different types of elements.
So far I have
public class AmmendmentPackage : BaseObject
{
public string Name {get;set;}
public string Description { get; set; }
public int MajorVersionNumber { get; set; }
public int MinorVersionNumber { get; set; }
public bool IsGazetted { get; set; }
public AmmendmentPackageState State { get; set; }
}
public 开发者_StackOverflow中文版class Ammendment<T>
{
public T AmmendedElement{get;set;}
public AmmendmentState State {get;set;}
public ConcurrencyDetails ConcurrencyState { get; set; }
}
How do I go about having the AmmendmentPackage contain number of different Ammentments of various types. I was thinking about using ICollection but then I would have an ICollection<Ammenndment<T>>
and I could only have one type of ammendment in the package.
Also was considering using a dictionary but not 100% sure how I would work that in just yet, hopefully I haven't missed something really basic but would appreciate some ideas.
Cheers
This is not possible.
You cannot have a strongly-typed collection that holds different types of objects.
Instead, you should make a non-generic base class or interface and make a collection of those.
You can create a collection of different concrete types that implement the same interface. If you make the interface definition empty, then it can even be applied to any reference type without modifying that type (but you'll have to figure out what operations are available on an AmmendedElement
at runtime - I don't recommend this, it is just possible). For example:
using System;
using System.Collections.Generic;
public interface IAnyType { }
public abstract class PackageBase { }
public class Class_1 : IAnyType { public string Class_1_String { get; set; } }
public class Class_2 : IAnyType { public string Class_2_String { get; set; } }
public class AmmendmentPackage : PackageBase
{
public IList<Ammendment<IAnyType>> Ammendments { get; set; }
}
public class Ammendment<T> where T : IAnyType
{
public T AmmendedElement { get; set; }
}
class Program
{
static void Main(string[] args)
{
Ammendment<IAnyType> ammendment_1 = new Ammendment<IAnyType>();
ammendment_1.AmmendedElement = new Class_1();
Ammendment<IAnyType> ammendment_2 = new Ammendment<IAnyType>();
ammendment_2.AmmendedElement = new Class_2();
AmmendmentPackage package = new AmmendmentPackage();
package.Ammendments = new List<Ammendment<IAnyType>>(2);
package.Ammendments.Add(ammendment_1);
package.Ammendments.Add(ammendment_2);
}
}
精彩评论