C#反射内存的处理分析

2019-12-26 11:11:43王旭

复制代码 internal class AssemblyLoader : MarshalByRefObject, IDisposable
{
#region class-level declarations
private Assembly a = null;
#endregion

 


#region constructors and destructors
public AssemblyLoader(string fullPath)
{
if (a == null)
{
a = Assembly.LoadFrom(fullPath);
}
}


~AssemblyLoader()
{
dispose(false);
}


public void Dispose()
{
dispose(true);
}


private void dispose(bool disposing)
{
if (disposing)
{
a = null;
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.GC.Collect(0);
}
}
#endregion
#region public functionality
public object GetObject(string typename, object[] ctorParms)
{
BindingFlags flags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;


object o = null
;
if (a != null)
{
try
{
o = a.CreateInstance(typename, true, flags, null, ctorParms, null, null);
}
catch
{
}
}
return o;
}


public object GetObject(string typename)
{
return GetObject(typename, null);
}
#endregion

 

public class ObjectLoader : IDisposable
{
// essentially creates a parallel-hash pair setup
// one appDomain per loader
protected Hashtable domains = new Hashtable();
// one loader per assembly DLL
protected Hashtable loaders = new Hashtable();


public ObjectLoader() 
{}


public object GetObject(string dllName, string typeName, object[] constructorParms)
{
AssemblyLoader al = null;
object o = null;
//Type t = null;
try
{
al = (AssemblyLoader)loaders[dllName];
}
catch (Exception) { }


if (al == null)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ShadowCopyFiles = "true";
AppDomain domain = AppDomain.CreateDomain(dllName, null, setup);
int key=0;
foreach (DictionaryEntry de in domains)
{
if(de.Key.ToString()==dllName)