所有,我有一个当前用于调用返回类型的 DLL 的方法bool
,这很好用。这种方法是
public static bool InvokeDLL(string strDllName, string strNameSpace,
string strClassName, string strMethodName,
ref object[] parameters,
ref string strInformation,
bool bWarnings = false)
{
try
{
// Check if user has access to requested .dll.
if (!File.Exists(Path.GetFullPath(strDllName)))
{
strInformation = String.Format("Cannot locate file '{0}'!",
Path.GetFullPath(strDllName));
return false;
}
else
{
// Execute the method from the requested .dll using reflection.
Assembly DLL = Assembly.LoadFrom(Path.GetFullPath(strDllName));
Type classType = DLL.GetType(String.Format("{0}.{1}",
strNameSpace, strClassName));
if (classType != null)
{
object classInstance = Activator.CreateInstance(classType);
MethodInfo methodInfo = classType.GetMethod(strMethodName);
if (methodInfo != null)
{
object result = null;
result = methodInfo.Invoke(classInstance, new object[] { parameters });
return Convert.ToBoolean(result);
}
}
// Invocation failed fatally.
strInformation = String.Format("Could not invoke the requested DLL '{0}'! " +
"Please insure that you have specified the namespace, class name " +
"method and respective parameters correctly!",
Path.GetFullPath(strDllName));
return false;
}
}
catch (Exception eX)
{
strInformation = String.Format("DLL Error: {0}!", eX.Message);
if (bWarnings)
Utils.ErrMsg(eX.Message);
return false;
}
}
现在,我想扩展这个方法,以便我可以从任何类型的 DLL 中检索返回值。我计划使用泛型来做到这一点,但立即进入了我不知道的领域。在编译时未知时如何返回 T,我查看了反射,但我不确定在这种情况下如何使用它。在上面的代码中进行第一次检查
public static T InvokeDLL<T>(string strDllName, string strNameSpace,
string strClassName, string strMethodName,
ref object[] parameters, ref string strInformation,
bool bWarnings = false)
{
try
{
// Check if user has access to requested .dll.
if (!File.Exists(Path.GetFullPath(strDllName)))
{
strInformation = String.Format("Cannot locate file '{0}'!",
Path.GetFullPath(strDllName));
return "WHAT/HOW??";
...
我怎样才能实现我想要的,或者我应该重载方法?
非常感谢您的帮助。