目前,我有这个代码:
var shellViewLibrary = Assembly.LoadFrom(Path.Combine(_DllsPath, _DllShellView));
IEnumerable<Type> types = shellViewLibrary.GetTypes();
foreach (Type type in types)
{
var typeIShellViewInterface = type.GetInterface(_NamespaceIShellView, false);
if (typeIShellViewInterface != null)
{
//here
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,//here我想用它Activator.CreateInstance来创建一个类型type 在特定文件夹(在build文件夹之外)的对象,我尝试了大约20种不同的东西,其中大部分是这样的:http://msdn.microsoft .com/zh-cn/library/d133hta4.aspx
但没有效果......我尝试过的典型事情是:
object MyObj = Activator.CreateInstance(shellViewLibrary.FullName, type.FullName);
Run Code Online (Sandbox Code Playgroud)
要么
object MyObj = Activator.CreateInstance(Path.Combine(_DllsPath, _DllShellView), type.FullName);
Run Code Online (Sandbox Code Playgroud)
我总是有不同的例外,最常见的是:
XamlParseException
Run Code Online (Sandbox Code Playgroud)
我觉得我没有使用Activator.CreateInstance以正确的方式使用2个参数.我该怎么办 ?
这是在运行时"从特定文件夹动态加载.dll"的示例.
// Check if user has access to requested .dll.
string strDllPath = Path.GetFullPath(strSomePath);
if (File.Exists(strDllPath))
{
// Execute the method from the requested .dll using reflection (System.Reflection).
Assembly DLL = Assembly.LoadFrom(strDllPath);
Type classType = DLL.GetType(String.Format("{0}.{1}", strNmSpaceNm, strClassNm));
if (classType != null)
{
// Create class instance.
classInst = Activator.CreateInstance(classType);
// Invoke required method.
MethodInfo methodInfo = classType.GetMethod(strMethodName);
if (methodInfo != null)
{
object result = null;
result = methodInfo.Invoke(classInst, new object[] { dllParams });
return result.ToString();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这需要一段时间才能解决,所以我希望它有一些用处......
一旦你打电话给这条线
var shellViewLibrary = Assembly.LoadFrom(Path.Combine(_DllsPath, _DllShellView));
Run Code Online (Sandbox Code Playgroud)
程序集已加载到内存中.只要您从中正确指定类型,就可以使用Activator.CreateInstance来创建类型.即:没有必要进一步明确,其中的类型是什么.
关于Activator,从MSDN,CreateInstance方法可以接受System.Type.我会在你的if语句中使用这个方法:
Activator.CreateInstance(Type type);
Run Code Online (Sandbox Code Playgroud)
我试图调试这个是首先创建类型,然后将其传递给CreateInstance.您可能会发现Type创建本身失败(由于未解析的程序集)或该类型的实例化(由于构造函数中的异常).乍一看,您的代码似乎是正确的:
foreach (Type type in types)
{
var typeIShellViewInterface = type.GetInterface(_NamespaceIShellView, false);
if (typeIShellViewInterface != null)
{
try
{
// I assume you are calling this line at the point marked 'here'.
// To debug the creation wrap in a try-catch and view the inner exceptions
var result = Activator.CreateInstance(type);
}
catch(Exception caught)
{
// When you hit this line, look at caught inner exceptions
// I suspect you have a broken Xaml file inside WPF usercontrol
// or Xaml resource dictionary used by type
Debugger.Break();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在你的问题中,你指定你得到一个XamlParseException.听起来像我所讨论的类型是UserControl(或者指的是WPF Xaml资源文件),并且该Xaml文件中存在错误,即与您对Assembly.Load或Activator.CreateInstance的使用无关.
您可以尝试发布内部异常以更好地了解问题所在吗?
| 归档时间: |
|
| 查看次数: |
13587 次 |
| 最近记录: |