如何在VB.NET或C#中在运行时从DLL创建类型的observablecollection [英] How to create observablecollection of a type from DLL at runtime in VB.NET or C#

查看:73
本文介绍了如何在VB.NET或C#中在运行时从DLL创建类型的observablecollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序集程序集 = Assembly.LoadFrom(  MyNice.dll); 

类型classType = 程序集 .GetType( MyType的);

object instanceOfMyType = Activator.CreateInstance(classType);

var lstProjects = new ObservableCollection(这里是instanceOfMyType的类型);?





我尝试过:



< pre>< pre> public  static 列表< T> MakeList< T>(T itemOftype)
{
List< T> newList = new List< T>();
return newList;
}





但它返回对象列表

解决方案

< blockquote>由于您在运行时加载.DLL而不是设置对它的引用,您将失去所有类型的安全性,包括使用 new ObservableCollection< MyType>()在你的代码中。像这样的泛型是编译时的概念,而不是运行时。



泛型类型,如 List< string> ,是一个语法糖,如果你愿意的话,这是一个捷径。为了编译该代码,您必须在编译时使用该类型,以便编译器可以在可执行文件中生成正确的代码。



既然你是在编译时不会有类型可用(没有引用),你必须自己创建代码来创建集合实例。请记住,在编写代码时,您仍然无法获得任何类型的安全性,也无法获得Intellisense的帮助。您获得的列表将是列表< object> ,而不是指定类型的列表。

  public   static   object  CreateListOfType(类型类型)
{
var listType = typeof运算(列表<>);
var listOfType = listType.MakeGenericType(type);
var instance = Activator.CreateInstance(listOfType);

return 实例;
}


Assembly assembly = Assembly.LoadFrom("MyNice.dll");

Type classType = assembly.GetType("MyType");

object instanceOfMyType = Activator.CreateInstance(classType);

 var lstProjects=new ObservableCollection(type of instanceOfMyType here);?



What I have tried:

<pre><pre>public static List<T> MakeList<T>(T itemOftype)
        {
            List<T> newList = new List<T>();
            return newList;
        }       



but it is returning list of object

解决方案

Since you're loading the .DLL at runtime instead of setting a reference to it, you loose all type safety, including the ability to use new ObservableCollection<MyType>() in your code. Generics like this are a compile-time concept, not run-time.

A generic type, like List<string>, is a bit of syntactic sugar, a shortcut if you will. In order for that code to compile, you MUST have the type available at compile-time so the compiler can generate the proper code in the executable.

Since you're not going to have the type available at compile time (no reference), you have to create the code to create the collection instance yourself. Keep in mind that you STILL will not get any type safety with this and no help from Intellisense when writing your code. The list you get back would be a List<object>, not a list of the specified type.

public static object CreateListOfType(this Type type)
{
    var listType = typeof(List<>);
    var listOfType = listType.MakeGenericType(type);
    var instance = Activator.CreateInstance(listOfType);

    return instance;
}


这篇关于如何在VB.NET或C#中在运行时从DLL创建类型的observablecollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆