全部,我有一个方法,目前用于调用返回类型的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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想扩展此方法,以便我可以从任何类型的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??";
...
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现我想要的,或者我只是重载方法?
非常感谢您的帮助.
更换
return false;
Run Code Online (Sandbox Code Playgroud)
通过
return default(T);
Run Code Online (Sandbox Code Playgroud)
和
return Convert.ToBoolean(result);
Run Code Online (Sandbox Code Playgroud)
通过
return (T)result;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
471 次 |
| 最近记录: |