Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Generic list question
Message
De
19/11/2014 07:49:21
 
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Versions des environnements
Environment:
C# 5.0
OS:
Windows 7
Network:
SAMBA Server
Database:
MS SQL Server
Application:
Desktop
Divers
Thread ID:
01611163
Message ID:
01611164
Vues:
64
>Hi All, I need to declare a generic list of a type which is decided at runtime, the type is one of several classes that all implement a common interface , I'm unsure how to do this, at first I thought I could use the Type of the class to create a list but this is not so - a small example of what I mean is shown below
>
>
>
>IMyInterFace  i = GetClassType();
>
>List<i> mylist = new List<i>();
>
>
>IMyInterFace GetClassType()
>{
>  if(SomeCondition)
>    return ClassA;
>  else
>    return classB;
>}
>
Think you have to cast to the interface, Pete

This compiles
	static class Test_GenericInterface
	{
		internal static void Go()
		{
			List<ITest> theList = new List<ITest>();

			theList.Add(GetElement(true));
		}
		static ITest GetElement( bool isFirst)
		{
			if (isFirst)
				return (ITest)(new ClassA());
			else
				return (ITest)(new ClassB());

		}
	}

	interface ITest
	{
		int Get();
	}
	class ClassA : ITest
	{
		public int Get()
		{
			return 1;
		}

	}
	class ClassB : ITest
	{
		public int Get()
		{
			return 3;
		}
	}
}
Gregory
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform