dim. 02 septembre 2012, 16h53
Gregory
atoutfox.public.association
Re: [c#] Créer un objet dynamiquement
> car j'avais un bug.
Il faut passer le nom complet de la classe - dans ton cas, je suppose
"Telerik.Reporting.ReportSource.Report.MandatSimple"
______
Gregory
______
"OlivierH" wrote in message news:k1vfkh$2he7$1@news.niouzes.net...
Ok , vraiment merci
je vais re tester cela lundi car j'avais un bug.
pour ta réponse en dessous, tu penses que l'on passer par cette solution ?
Olivier
Le 01/09/12 13:44, Gregory Adam a écrit :
> Deuxieme correction
namespace CoreTest
{
public static class ObjectCreator
{
static Dictionary<string, Type> Cache = new Dictionary<string, Type>();
static object Locker = new object();
public static object GetNew(string classname)
{
// try cache
Type type;
if (Cache.TryGetValue(classname, out type))
{
if (type == null)
return null;
else
return type.InvokeMember(null, BindingFlags.Public | BindingFlags.Instance
| BindingFlags.CreateInstance, null, null, null);
}
else
{
bool success = (type = DrillDownAssemblies(classname)) != null;
object o = null ;
if (success)
{
try // just in case
{
o = type.InvokeMember(null, BindingFlags.Public | BindingFlags.Instance |
BindingFlags.CreateInstance, null, null, null);
}
catch
{
o = null;
}
}
// add to Cache for next time
lock (Locker)
{
Cache.Add(classname, o == null ? null : type);
}
return o;
}
}
private static Type DrillDownAssemblies(string classname)
{
HashSet<string> visited = new HashSet<string>();
Queue<string> todo = new Queue<string>();
Assembly assembly = Assembly.GetExecutingAssembly();
todo.Enqueue(assembly.FullName);
while (todo.Count != 0)
{
string assemblyFullName = todo.Dequeue();
visited.Add(assemblyFullName);
var assemblyLoaded = Assembly.Load(assemblyFullName);
// add referenced assemblies that have not been processed
foreach ( var x in assemblyLoaded.GetReferencedAssemblies() )
if( !visited.Contains(x.FullName) )
todo.Enqueue(x.FullName) ;
Type type ;
if ((type = assemblyLoaded.GetType(classname, false)) == null)
continue;
ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
return constructor == null ? null : type;
}
return null;
}
}
}
>
>
Permalink : http://www.atoutfox.org/nntp.asp?ID=0000009699