轉自:http://blog.csdn.net/mm33211/article/details/8143890
C# 根據對象類完整名稱,建立對象執行個體
/// <summary>
/// 根據指定的類全名,傳回對象執行個體
/// </summary>
/// <param name="objFullName">對象完整名稱(包名和類名),如:com.xxx.Test</param>
public object createObjectInstance(string objFullName)
{
//擷取目前目錄
string currentDir = Assembly.GetExecutingAssembly().Location;
currentDir = currentDir.Substring(0, currentDir.LastIndexOf('\\'));
DirectoryInfo di = new DirectoryInfo(currentDir);
//擷取目前目錄下的所有DLL檔案
FileInfo[] files = di.GetFiles("*.dll");//隻查.dll檔案
//周遊所有檔案,查找需要對象的實作定義
Type type = Type.GetType(objFullName);
if (type == null)
{
foreach (FileInfo fi in files)
{
type = getObjectType(fi.FullName, objFullName);
if (type != null)
{
break;
}
}
}
if (type == null)
{
//throw new Exception("can not find class define of " + objFullName);
return null;
}
//将對象執行個體化
object obj=Activator.CreateInstance(type);
return obj;
}
/// <summary>
/// 從DLL檔案中查找指定的對象定義
/// </summary>
/// <param name="dllFile">DLL檔案路徑</param>
/// <param name="objFullName">對象完整名稱(包名和類名),如:com.xxx.Test</param>
/// <returns>如果找到,傳回其對應的Type;如果沒找到,則傳回null</returns>
private Type getObjectType(string dllFile, string objFullName)
{
Type type = Assembly.LoadFile(dllFile).GetType(objFullName);
if (type != null)
{
Console.WriteLine("find obj in dll[" + dllFile + "]");
return type;
}
return null;
}
轉載于:https://www.cnblogs.com/bluemaplestudio/p/4114612.html