Se ho capito bene, si sta tentando di memorizzare una raccolta di tipi generici, in cui i parametri di tipo generico possono variare. Se questo è il caso, non è direttamente possibile, come il seguente esempio illustra:
// You have lists of different types:
List<double> doubleCollection = new List<double>();
List<string> stringCollection = new List<string>();
// Now to store generically:
var collection = new List<List< /* ... Which type parameter to use? ... */ >>();
quello che dovrebbe essere evidente qui, è che non è possibile dedurre quale parametro tipo usare. Invece (per quanto riguarda il tuo esempio), si può decidere qualcosa di simile a questo, invece:
public interface IOperand
{
}
public interface IOperand<T>
{
}
public interface IOperandFactory
{
IOperand CreateEmptyOperand();
IOperand CreateOperand(object value);
}
public interface IOperandFactory<T> : IOperandFactory
{
new IOperand<T> CreateEmptyOperand();
IOperand<T> CreateOperand(T value);
}
public class DoubleFactory : IOperandFactory<double>
{
public IOperand<double> CreateEmptyOperand()
{
throw new NotImplementedException();
}
public IOperand<double> CreateOperand(double value)
{
throw new NotImplementedException();
}
IOperand IOperandFactory.CreateEmptyOperand()
{
throw new NotImplementedException();
}
public IOperand CreateOperand(object value)
{
throw new NotImplementedException();
}
}
public class SomeContainer
{
public SomeContainer()
{
var factoryDict = new Dictionary<Type, IOperandFactory>()
{
{ typeof(double), (IOperandFactory)new DoubleFactory() }
};
}
}
Questo non può essere il più elegante di soluzioni, ma permetterebbe di memorizzare diversi tipi generici nella stessa collezione. Un problema con questo, tuttavia, è che il chiamante che accede a una raccolta di questo tipo avrebbe bisogno di sapere a quale tipo eseguire il cast. Per esempio:
// ... Inside SomeContainer ...
public IOperandFactory<T> GetFactory<T>()
{
return (IOperandFactory<T>)factoryDict[typeof(T)];
}
Quindi, con questo, è possibile ottenere il DoubleFactory
utilizzando:
IOperandFactory<double> doubleFactory = mSomeContainerInstance.GetFactory<double>();
IOperand<double> emptyOperand = doubleFactory.CreateEmptyOperand();
IOperand<double> filledOperand = doubleFactory.CreateOperand(1.0d);
fonte
2012-01-16 09:11:32
Grazie per la risposta rapida. – Danil
@Danil Ho modificato un esempio completo, se aiuta –
Sì, grazie, penso che sarà utile anche per altri utenti. – Danil