This is probably a classic covariance/contravariance question, it looks like it should work but I'm probably missing a trick.
I'm attempting to return a less derived type from a factory method, but I find that I cannot cast the more specialized concrete instance to a less derived base type.
public class AnimalSettings { ... }
public class CatSettings : AnimalSettings { ... }
public interface IAnimalService<TSettings> { ... }
public abstract AnimalService<TSettings> : IAnimalService<TSettings> where TSettings : AnimalSettings { ... }
public class CatService : AnimalService<CatSettings> { ... }
Then, in a factory method I have:
public static IAnimalService<AnimalSettings> GetAnimalService(AnimalType selector)
{
switch (selector)
{
case AnimalType.Cat:
return (IAnimalService<AnimalSettings>) new CatService();
break;
}
}
and the intention is to be able to do the following:
var service = MyServiceFactory.GetAnimalService(AnimalType.Cat);
service.DoAnimalBehavior();
This compiles fine, but at runtime my code is failing in the attempted cast return (IAnimalService<AnimalSettings>) new CatService();, with an InvalidCastException.
How should I be casting my more derived type to a less derived type so that callers can use that interfaced base type to invoke functionality?
Changing the cast to (IAnimalservice<CatSettings>) new CatService() does work, but it's intended that the caller receives a IAnimalservice<AnimalSettings> so that it can handle any sort of animal (In other words, the caller should not be using any of the more specialized types). Should I be specifying an in or out as part of the generic definition somewhere?
By giving a complete example it would be much easier to help. ;-)
So here is the working code. And as Sweeper already mentioned, you need to add the out parameter at the interface to make it work.
using System;
public class Program
{
public static void Main()
{
var catService = new CatService(new CatSettings());
var genericService = (IAnimalService<AnimalSettings>)catService;
genericService.DoAnimalBehavior();
}
}
public abstract class AnimalSettings
{
public abstract void DoAnimalBehavior();
}
public class CatSettings : AnimalSettings
{
public override void DoAnimalBehavior()
{
Console.WriteLine("Meeoh");
}
}
public interface IAnimalService<out TSettings>
{
void DoAnimalBehavior();
}
public abstract class AnimalService<TSettings> : IAnimalService<TSettings> where TSettings : AnimalSettings
{
private readonly TSettings _settings;
public AnimalService(TSettings settings)
{
_settings = settings;
}
public void DoAnimalBehavior()
{
_settings.DoAnimalBehavior();
}
}
public class CatService : AnimalService<CatSettings>
{
private readonly CatSettings _catSettings;
public CatService(CatSettings catSettings)
: base(catSettings)
{
_catSettings = catSettings;
}
}
Related
I have the following class relationships
public interface ICapability
{
}
public interface IBaseService<T> where T : ICapability
{
}
public abstract class BaseService<out T> : IBaseService<T> where T : ICapability
{
// modified...
T MapEventToCapability(dynamic eventData, T capability);
}
public class SomeCapability : ICapability
{
}
public partial class Service1 : BaseService<SomeCapability>
{
public Service1()
{
}
}
public class ServiceResolver
{
public void Register(BaseService<ICapability> serviceToRegister)
{
}
}
I try to invoke the Register method, passing in a new service1 as shown:
var b = new ServiceResolver();
var c = new Service1();
b.Register(c);
However I get a compile time error on c in the call to Register as follows;
Cannot convert Service1 to BaseService<ICapability>
I assumed that because Service1 is of type BaseService and that since SomeCapability is of type ICapability that this wouldn't be an issue.
I tried casting to BaseService as well I tried changing the input parameter on Register to be an IBaseService and again casting but then I get a runtime error.
Note the question has been updated since this answer was posted - covariance is no longer an option having added a method which is incompatible
You'll need to do 2 things to make this work
Make Register take IBaseService<ICapability> not BaseService<ICapability>
Make IBaseService covariant by marking the generic type as out - this is the same as the reason you can pass a List<Foo> to a merthod which expects an IEnumerable<Foo> as IEnumerable<T> is covariant in a similar manner.
public class ServiceResolver
{
public void Register(IBaseService<ICapability> serviceToRegister)
{
}
}
and
public interface IBaseService<out T>
where T : ICapability
{
}
Live example: https://dotnetfiddle.net/O0yXa5
I have got two abstract classes: Particle and ParticleHub<T> where T : Particle.
I want, when I inherit Particle, for its constructor to require a ParticleHub of its respective type to be passed as a parameter. I want its constructor to be like this:
ParticleHub</*type of the inheriting class*/> _particleHub;
public Particle(ParticleHub</*type of the inheriting class*/> particleHub, OtherParameters otherParameters)
{
_particleHub = particleHub;
//use other parameters
}
If I write ParticleHub<typeof(this)> I get overloaded with errors that make me think I broke the syntax for the rest of the file. If I do ParticleHub<this.GetType()> I get the same problem, but only with fewer errors. Though with that one, I can understand that I can't use a function in a parameter type like that.
So how do I go about this?
Simple example below of an interface and generic pattern
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
IChair chair = new Chesterfield<Arm>(new Arm());
chair.Sit();
Console.Write(chair.HasSat());
}
}
public interface IChair
{
void Sit();
bool HasSat();
}
public interface IPart
{
}
public class Chesterfield<TPart> : Chair<TPart> where TPart : IPart
{
public Chesterfield(TPart part) => _part = part;
private bool _hasSat;
private readonly TPart _part;
public override void Sit()
{
_hasSat = true;
}
public override bool HasSat() => _hasSat;
}
public abstract class Chair<TPart> : IChair where TPart : IPart
{
public abstract void Sit();
public abstract bool HasSat();
}
public class Arm : IPart
{
}
public class Back : IPart
{
}
public class Leg
{
}
You have no other choise i think but to pass the type as other generic. See the exaple how it is done in terms of fluent builders as I think it is very close what You want to have: Link.
Like:
FePatricle<T, U> where T: Particle, U: FeParticle<T, U>
Looks crazy but it should do the trick in the constructor:
public FeParticle(ParticleHub<U>...
EDIT:
Or more likely as far as I understand:
FePatricle<T>: Particle where T: FeParticle<T>
So FePartivle extends Particle and it carries with itself its own type T?
Passing the inherited class itself, as below.
public abstract class Particle
{
}
public abstract class ParticleHub<T> where T : Particle
{
}
public class k1 : Particle
{
ParticleHub<k1> _particleHub = null;
public k1(ParticleHub<k1> ph)
{
_particleHub = ph;
}
}
I was using generic types in C# and I am new to using generic types. So, right now I am stuck with a problem. I have some classes like these:
public class MyModel1
{
}
public class MyModel2
{
}
public class BaseClass<T>
{
}
public class ChildClass1 : BaseClass<MyModel1>
{
}
public class ChildClass2 : BaseClass<MyModel2>
{
}
public class AnotherClass
{
//What will be the syntax of declaring this method
//The syntax of the following method is wrong and incomplete.
//It's there just to give an idea about whai i want to do.
public void MyMethod<T>()
where T : BaseClass<..what to write..>
{
}
}
My question is what will be the correct syntax of declaring MyMethod if I want to call MyMethod like this:
MyMethod<ChildClass1>();
If I understood correctly, you try to filter "MyMethod" so that T is a class of type "ChildClass ...".
You can add a generic parameter to your function like this:
public void MyMethod<T, U>()
where T : BaseClass<U>
{
}
But then you have to call MyMethod in that way.
MyMethod<ChildClass1, MyModel1>();
So it's quite complicated to use.
Another solution is to create a new "blank" class :
public abstract class Base // mark it as abstract if you don't need to use it in your code
{
}
public class MyModel1
{
}
public class MyModel2
{
}
public class BaseClass<T> : Base //The class inherits the new class
{
}
public class ChildClass1 : BaseClass<MyModel1>
{
}
public class ChildClass2 : BaseClass<MyModel2>
{
}
public class AnotherClass
{
public void MyMethod<T>()
where T : Base
{
}
}
You've forgotten to mention the return type and adding <T> after the class name. For example, if the return type is void, you could declare the method as:
public void MyMethod<T>()
where T : BaseClass<T>
{
}
This will work (by which I mean it compiles)
public void MyMethod<T>()
where T : BaseClass<MyModel1>
{ }
so does this:
public void MyMethod<T>()
where T : ChildClass1
{ }
Further edit after reading your comment...
You can do this:
public class AnotherClass<TBaseClass, TModel> where TBaseClass : BaseClass<TModel>
{
public void MyMethod(TBaseClass input)
{ }
}
I have a term for this, hopefully non-offensive. I call it The Generic Rabbit Hole of Madness. It's what happens when we try to combine generics and inheritance so that one set of classes can accomplish a broad set of goals that become increasingly confusing, and we solve it by adding more generic parameters and more generic classes.
You reach the bottom of the hole if you
- use <dynamic>
- check to see what the actual type is using GetType(), typeof, or is
- get it to compile but can't remember what it's supposed to do
I have a generic class who holds a member whose type is an argument type.
I want to be able to access this member only by one of the interface it implements.
The reason I want to access the member only via this interface, instead of enumerating all the concrete types it could be, is because there are a great number of those types.
So concretely I want to find an equivalent of line 61 in that code (it is a compilation error):
using System;
using System.Linq;
/* Interfaces */
public interface IArgumentClass
{
void IArgumentClassMethod();
}
public interface ISpecialArgumentClass
{
void ISpecialArgumentClassMethod();
}
public interface IContainerClass
{
void IContainerClassClassMethod();
}
/* Argument types */
public class ArgumentClass0 : IArgumentClass
{
public void IArgumentClassMethod(){}
}
public class SpecialArgumentClass0 : IArgumentClass, ISpecialArgumentClass
{
public void IArgumentClassMethod(){}
public void ISpecialArgumentClassMethod(){}
}
public class SpecialArgumentClass1 : IArgumentClass, ISpecialArgumentClass
{
public void IArgumentClassMethod() { }
public void ISpecialArgumentClassMethod() { }
}
/* Container types */
public class GenericContainer<T> : IContainerClass
where T : IArgumentClass, new()
{
public T t = new T();
public void IContainerClassClassMethod() { }
}
public class NonGenericContainer : IContainerClass
{
public void IContainerClassClassMethod(){}
}
/* main program */
public class Test
{
public static void Main()
{
// Instantiate
IContainerClass[] containers =
{
new GenericContainer<ArgumentClass0>(),
new GenericContainer<SpecialArgumentClass0>(),
new GenericContainer<SpecialArgumentClass1>(),
new NonGenericContainer()
};
// We want to call IContainerClassClassMethod methods on all instances:
foreach (IContainerClass container in containers)
container.IContainerClassClassMethod();
// We want to call ISpecialArgumentClassMethod on instances where it's possible:
foreach (IContainerClass container in containers)
{
if (container.GetType().IsGenericType && container.GetType().GetGenericTypeDefinition() == typeof(GenericContainer<>))
{
foreach (Type typeArgument in container.GetType().GetGenericArguments())
{
if (typeArgument.GetInterfaces().Contains(typeof(ISpecialArgumentClass)))
{
// Next line is a compilation error. How can I get a similar result?
GenericContainer<ISpecialArgumentClass> mySpecializedClassWithSpecialArgument = container as GenericContainer<ISpecialArgumentClass>;
mySpecializedClassWithSpecialArgument.t.ISpecialArgumentClassMethod();
}
}
}
}
}
}
Note: You can fork and edit the code here.
You get the compilation error because ISpecialArgumentClass is not of type IArgumentClass, but your GenericClass requires exactly this.
To solve this, you could introduce an empty interface which serves as base for both argument classes:
First, modify your interface declaration like this:
public interface IArgumentClassBase
{
}
public interface IArgumentClass : IArgumentClassBase
{
String GetNormalString();
}
public interface ISpecialArgumentClass : IArgumentClassBase
{
String GetSpecialString();
}
... then modify your generic class declaration like so:
public class GenericClass<T> : IContainerClass
where T : IArgumentClassBase, new()
Then the rest of your code should work...
A really simple solution is to just cast it to dynamic - you know it has a t field, so this should be safe to do.
if (typeArgument.GetInterfaces().Contains(typeof(ISpecialArgumentClass)))
{
dynamic mySpecializedClassWithSpecialArgument =
mySpecializedClass as dynamic;
ISpecialArgumentClass specialArgumentClass = mySpecializedClassWithSpecialArgument.t;
Console.WriteLine(specialArgumentClass.GetSpecialString());
}
Note
I tried to edit it in ideone, but it would not compile. I suspect it's targeting an older version of .NET - dynamic was introduced in .NET 4 (VS 2010). However, I've tested the code in 2013 and it works.
I know I'm not doing this right, but I also know there is a way to do this. I'm trying to be as generic and abstract as possible, otherwise my code is going to get real messy. So I'm using strategy pattern here as well, which is the GetAggregateClient() method.
I want to have an abstract class called AbstractAggregate<T>, so that it uses generics. The generic type will be a series of data classes (BlogItem, ResourceItem, and AskItem), which all inherit from ListItem.
So that's the background info.
The problem here is that I want GetAbstractAggregate() to return an instance of one of the client classes that implements AbstractAggregate, with the type of item specified depending on the enum passed in. However, I cannot return an AbstractAggregate<T>. The compiler won't let me, and that makes sense since, since the AbstractAggregateFactory class is not a generic.
Does anyone know the best way to do this?
Thanks a lot.
public static class AggregateHelper
{
public enum AggregateTypes { TankTruckBlog, AskTankTruck, Resources }
}
public static class AbstractAggregateFactory
{
public static AbstractAggregate<T> GetAggregateClient(AggregateHelper.AggregateTypes type)
{
switch (type)
{
case AggregateHelper.AggregateTypes.AskTankTruck:
return new AskTankTruckAggregate<AskItem>();
case AggregateHelper.AggregateTypes.TankTruckBlog:
return new TankTruckBlogAggregate<BlogItem>();
case AggregateHelper.AggregateTypes.Resources:
return new ResourcesAggregate<ResourceItem>();
default:
throw new AggregateDoesNotExistException();
}
}
}
public abstract class AbstractAggregate<T>
{
public abstract List<T> GetAggregate(Guid[] resourcetypes);
public abstract T GetSingle(string friendlyname);
}
public class AskTankTruckAggregate<T> : AbstractAggregate<T>
{
// not implemented yet
}
public class TankTruckBlogAggregate<T> : AbstractAggregate<T>
{
// not implemented yet
}
public class ResourcesAggregate<T> : AbstractAggregate<T>
{
// not implemented yet
}
The problem the compiler complains about is that you have a method which is 'open' (T) - and you're returning closed generic (with <AskItem> etc.), concrete type really.
i.e. you have to return a <T> - and you can do that with the method - no matter if the factory is not generic, the method still can be.
As for what's the best way to do it, that's more of a design question, and a bit longer story. I'm not entirely sure what you're trying to achieve (maybe some background story, how many types you might have etc.)
First, your items shouldn't (generally speaking, as a best practice or some 'feels good' factor) inherit from ListItem. Use some other base class of yours, and if you need a collection, use a generic one like List<T>, or create your own IList implementation, etc.
Second, you don't need to make everything generic. Your base aggregator is generic but custom classes are not, usually. For example:
abstract class ItemBase { }
class AskItem : ItemBase { }
class BlogItem : ItemBase { }
class ProvderA : ProviderBase<AskItem>
{
public override AskItem Get()
{
throw new NotImplementedException();
}
}
class ProvderB : ProviderBase<BlogItem>
{
public override BlogItem Get()
{
throw new NotImplementedException();
}
}
abstract class ProviderBase<T> where T : ItemBase
{
public abstract T Get();
}
class Program
{
static void Main(string[] args)
{
ProviderBase<AskItem> provider = GetProvider<AskItem>();
var item = provider.Get();
}
static ProviderBase<T> GetProvider<T>() where T : ItemBase
{
if (typeof(T) == typeof(AskItem))
return (ProviderBase<T>)(object)new ProvderA();
if (typeof(T) == typeof(BlogItem))
return (ProviderBase<T>)(object)new ProvderB();
return null;
}
}
...that's one implementation.
Basically, making everything 'generic' is not always the best way. You have to have enough reasons or 'types' unknown to be possibly used. As with generic you also pay a certain price. Crossing generics to non-generics world is often tricky, and involves reflection if your types can't be inferred by the usage etc.
In my opinion, it's a mistake making each provider generic (<T>), as it only accepts one type (each concrete), while base is generic. So like the above. Usually generic is also constrained per interface where/where you can.
But then you have a problem, as casting back to generic context from effectively a non-generic class is not straight (also have in mind there are caveats with value types as you often have to treat that differently), and vice versa as well.
Hence you need something like cast (object) first.
I'd rather use sort of an IOC approach here - e.g. look at the autofac (I'm not associated but I like how it works, nice framework). In that case you'd do something like this:
container.Register<ProviderBase<AskItem>>(c=> new ProvderA());
container.Register<ProviderBase<BlogItem>>(c => new ProvderB());
// and query later...
ProviderBase<AskItem> provider = container.Resolve<ProviderBase<AskItem>>();
Hope this helps some.
I'm not sure I understand what you are trying to achieve but perhaps it's something like this
public static class AbstractAggregateFactory
{
public static AbstractAggregate<T> GetAggregateClient<T>()
{
if(T is AskItem) return new AskTankTruckAggregate();
if(T is BlogItem) return new TankTruckBlogAggregate();
if(T is ResourceItem) return new ResourcesAggregate();
}
}
public abstract class AbstractAggregate<T>
{
public abstract List<T> GetAggregate(Guid[] resourcetypes);
public abstract T GetSingle(string friendlyname);
}
public class AskTankTruckAggregate : AbstractAggregate<AskItem>
{
//not implemented yet
}
public class TankTruckBlogAggregate : AbstractAggregate<BlogItem>
{
//not implemented yet
}
public class ResourcesAggregate : AbstractAggregate<ResourceItem>
{
//not implemented yet
}
I'm trying to be as generic and abstract as possible, otherwise my code is going to get real messy.
this is a misconception. being generic/abstract can actually complicate an otherwise simple problem. The key to clean code is encapsulation. much different that inheritance or generics.
In this case I think composition would be a better choice, rather than inheritance. with a set of adaptors you could have a common object that each entity could be adpated to. for example:
interface ICommon { ... }
class AskAdaptor: ICommon
{
private readonly Ask ask;
publick AskAdaptor(Ask ask)
{
this.ask = ask;
}
}
class AskAdaptor: ICommon
{
private readonly Blog blog;
publick AskAdaptor(Blog blog)
{
this.blog = blog;
}
}
class AskAdaptor: ICommon
{
private readonly Resource resource;
publick AskAdaptor(Resource resource)
{
this.resource = resource;
}
}
class CommonAggregate
{
public void Add(ICommon common)
{
....
}
}
How about this:
public static class AggregateHelper
{
public enum AggregateTypes { TankTruckBlog, AskTankTruck, Resources }
}
public class AskItem { }
public class BlogItem { }
public class ResourceItem { }
public static class AbstractAggregateFactory
{
public static AbstractAggregate<T> GetAggregateClient<T>
(AggregateHelper.AggregateTypes type)
{
switch (type)
{
case AggregateHelper.AggregateTypes.AskTankTruck:
return new AskTankTruckAggregate<T>();
case AggregateHelper.AggregateTypes.TankTruckBlog:
return new TankTruckBlogAggregate<T>();
case AggregateHelper.AggregateTypes.Resources:
return new ResourcesAggregate<T>();
default:
throw new ArgumentException();
}
}
}
public abstract class AbstractAggregate<T>
{
public abstract List<T> GetAggregate(Guid[] resourcetypes);
public abstract T GetSingle(string friendlyname);
}
public class AskTankTruckAggregate<T> : AbstractAggregate<T>
{
public override List<T> GetAggregate(Guid[] resourcetypes)
{
throw new NotImplementedException();
}
public override T GetSingle(string friendlyname)
{
Console.WriteLine(friendlyname);
Type whats_t = typeof(T);
return default(T);
}
}
public class TankTruckBlogAggregate<T> : AbstractAggregate<T>
{
//not implemented yet
}
public class ResourcesAggregate<T> : AbstractAggregate<T>
{
//not implemented yet
}
Example:
AbstractAggregate<BlogItem> foo3 =
AbstractAggregateFactory.GetAggregateClient<BlogItem>(AggregateHelper.AggregateTypes.AskTankTruck);
foo3.GetSingle("test");
One thing that is possibly clear is that your design is somewhat flawed. A switch on type is not the best thing to do in a generic method which defeats it's purpose. But what is not clear is what the purpose of your classes are.
Some speculations:
1) Seeing your pair classes AskItem and AskTankTruckAggregate<T> etc I dont think the latter has to be a generic class, it is a very specific class, tightly coupled to AskItem. I would redesign it like
public static class AbstractAggregateFactory
{
public static AbstractAggregate<T> GetAggregateClient<T>() where T : ListItem
{
//use reflection to find the type that inherits AbstractAggregate<T>
//instantiate the type
//cast to AbstractAggregate<T> and return
}
}
public class AskTankTruckAggregate : AbstractAggregate<AskItem>
{
//not implemented yet
}
public class TankTruckBlogAggregate : AbstractAggregate<BlogItem>
{
//not implemented yet
}
public class ResourcesAggregate : AbstractAggregate<ResourceItem>
{
//not implemented yet
}
Call it like:
AbstractAggregateFactory.GetAggregateClient<AskItem>(); //etc
2) Another way: delegate the aggregate creation job to your ListItems.
public abstract class ListItem //or interface
{
protected abstract object Create();
}
public class AskItem : ListItem { //implement to return AskTankTruckAggregate
}
public class BlogItem : ListItem { //implement to return TankTruckBlogAggregate
}
public class ResourceItem : ListItem { //implement to return ResourcesAggregate
}
public static class AbstractAggregateFactory
{
public static AbstractAggregate<T> GetAggregateClient<T>() where T : ListItem, new()
{
return (AbstractAggregate<T>)new T().Create();
}
}
public class AskTankTruckAggregate : AbstractAggregate<AskItem>
{
//not implemented yet
}
public class TankTruckBlogAggregate : AbstractAggregate<BlogItem>
{
//not implemented yet
}
public class ResourcesAggregate : AbstractAggregate<ResourceItem>
{
//not implemented yet
}
Call it like:
AbstractAggregateFactory.GetAggregateClient<AskItem>(); //etc
3) Or the same, but make it a bit more strongly typed, with the use of generics:
public abstract class ListItem<T> where T : ListItem<T> //or interface
{
protected abstract AbstractAggregate<T> Create();
}
public class AskItem : ListItem<AskItem> { //implement to return AskTankTruckAggregate
}
public class BlogItem : ListItem<BlogItem> { //implement to return TankTruckBlogAggregate
}
public class ResourceItem : ListItem<ResourceItem> { //implement to return ResourcesAggregate
}
public static class AbstractAggregateFactory
{
public static AbstractAggregate<T> GetAggregateClient<T>() where T : ListItem, new()
{
return new T().Create();
}
}
public class AskTankTruckAggregate : AbstractAggregate<AskItem>
{
//not implemented yet
}
public class TankTruckBlogAggregate : AbstractAggregate<BlogItem>
{
//not implemented yet
}
public class ResourcesAggregate : AbstractAggregate<ResourceItem>
{
//not implemented yet
}
Call it like:
AbstractAggregateFactory.GetAggregateClient<AskItem>(); //etc
4) Lastly, may be make the return type less generic? Involves switch case, I dont like it.
public enum AggregateTypes { TankTruckBlog, AskTankTruck, Resources }
public static class AbstractAggregateFactory
{
public static AbstractAggregate GetAggregateClient(AggregateTypes type)
{
switch (type)
{
case AggregateTypes.AskTankTruck:
return new AskTankTruckAggregate<AskItem>();
case AggregateTypes.TankTruckBlog:
return new TankTruckBlogAggregate<BlogItem>();
case AggregateTypes.Resources:
return new ResourcesAggregate<ResourceItem>();
default:
throw new AggregateDoesNotExistException();
}
}
}
public abstract class AbstractAggregate
{
}
public abstract class AbstractAggregate<T> : AbstractAggregate
{
}
//or change the definition to AskTankTruckAggregate : AbstractAggregate<AskItem>
public class AskTankTruckAggregate<T> : AbstractAggregate<T>
{
//not implemented yet
}
//or change the definition to TankTruckBlogAggregate : AbstractAggregate<BlogItem>
public class TankTruckBlogAggregate<T> : AbstractAggregate<T>
{
//not implemented yet
}
//or change the definition to ResourcesAggregate : AbstractAggregate<ResourceItem>
public class ResourcesAggregate<T> : AbstractAggregate<T>
{
//not implemented yet
}
Call it like:
AbstractAggregateFactory.GetAggregateClient(AggregateTypes.AskTankTruck); //etc
Imo, this approach is worse than the reflection approach. Its easy to forget some enum checking in future.
Of all, 3rd looks the best to my eyes, but again without knowing your design goal, its very difficult to predict. Few suggestions:
Your factory name sounds better like AggregateFactory. "Abstract" in it makes it more about implementation.
In case you need an enum to denote type, do not make it nested. Nested public types are harder to call. Take out the wrapping static class (as in my 5th approach).
Rename your base class as Aggregate<T> or AggregateBase<T>. Again "Abstract" in it makes it more about implementation, quite needless.