通过提供类名作为字符串来获取引用程序集中的类型? [英] Get type in referenced assembly by supplying class name as string?

查看:21
本文介绍了通过提供类名作为字符串来获取引用程序集中的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是类似的问题:操作方法:在运行时使用 Silverlight 中的字符串从引用的程序集中加载类型对引用程序集中的类进行 GetType 失败,但两个答案都不起作用.

These are similar questions: How-to: Load a type from a referenced assembly at runtime using a string in Silverlight, GetType on a class in a referenced assembly fails but neither answer works.

我有一个 MVC 项目,它从一个数据库中提取数据,该数据库包含作为字符串的普通类型.这些类型在引用的程序集中,而不是在 MVC 项目中.

I've got an MVC project that pulls data from a database that includes the plain types as strings. These types are in a referenced assembly, not in the MVC project.

例如,假设我的引用程序集名称是 MyFramework 和普通类型名称 Car,完整的类型名称可以是 MyFramework.Cars.CarMyFramework.Vehicles.Cars.Car 或其他一些变体.我所拥有的只是作为字符串的引用程序集名称和普通类名称.无论完整的类型名称如何,如何获取类型?

So for example let's say my Referenced Assembly Name is MyFramework and the plain type name Car, the full type name could be MyFramework.Cars.Car or MyFramework.Vehicles.Cars.Car or some other variation. All I have are the referenced assembly name and plain class name as strings. How can I get the type regardless of the full type name?

最后,我可以在引用的程序集中编写一个调用 GetType() 的函数并在 MvC 项目中使用它,以便我可以放弃包含程序集名称吗?我想删除知道程序集名称的信息,所以我想我可以在引用的程序集中编写一个 Util ,例如:

Finally, could I write a function in the referenced assembly that calls GetType() and use that in the MvC project so I could forego including the assembly name? I want to remove knowing the assembly name so I thought I could write a Util IN the referenced assembly like:

namespace MyFramework //the referenced assembly
{
  public static class TypeUtil
  {
    public static Type GetFrameworkType(string typeName)
    {
        return Type.GetType(typeName);
    }
  }
}

然后在我的 MVC 项目中,我可以在不需要程序集作为字符串名称的情况下调用它.这是可能的还是我总是需要程序集名称?

And then in my MVC project I could call it without needing the assembly as a string name. Is that possible or will I always need the assembly name?

推荐答案

可能当时没有加载引用的程序集.另外,我从您的问题中了解到您没有完整的类型名称,只有类名.
你应该尝试沿着这条线做一些事情:

Maybe the referenced assembly isn't loaded at the time. Also, I understand from your question that you do not have the full type name, only the class name.
You should try something along this line then:

Type type = Assembly.Load("YourAssemblyName").GetTypes().First(t => t.Name == "ShortTypeName");

希望我理解正确.

这篇关于通过提供类名作为字符串来获取引用程序集中的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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