简体   繁体   English

通过将类名作为字符串提供来获取引用程序集中的类型?

[英]Get type in referenced assembly by supplying class name as string?

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.这些是类似的问题: 操作方法:在运行时使用 Silverlight 中的字符串从引用程序集中加载类型,引用程序集中类上的 GetType 失败,但两个答案均无效。

I've got an MVC project that pulls data from a database that includes the plain types as strings.我有一个 MVC 项目,它从一个数据库中提取数据,其中包括作为字符串的普通类型。 These types are in a referenced assembly, not in the MVC project.这些类型在引用的程序集中,而不是在 MVC 项目中。

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.因此,例如,假设我的引用程序集名称是MyFramework和普通类型名称Car ,完整类型名称可以是MyFramework.Cars.CarMyFramework.Vehicles.Cars.Car或其他一些变体。 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?无论完整的类型名称如何,我如何获得类型?

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?最后,我能否在调用 GetType() 的引用程序集中编写一个函数并在 MvC 项目中使用它,这样我就可以放弃包含程序集名称? I want to remove knowing the assembly name so I thought I could write a Util IN the referenced assembly like:我想删除知道的程序集名称,所以我想我可以在引用的程序集中编写一个 Util,例如:

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

And then in my MVC project I could call it without needing the assembly as a string name.然后在我的 MVC 项目中我可以调用它而不需要程序集作为字符串名称。 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");

Hope I understood you correctly.希望我理解正确。

For the first question, you could do something like对于第一个问题,你可以做类似的事情

Type t = AppDomain.CurrentDomain.GetAssemblies()
                                .Where(a => a.FullName == "MyFramework")
                                .SelectMany(a => a.GetTypes())
                                .FirstOrDefault(t => t.Name == "Car");

I am not sure what you mean by the second question.我不确定你说的第二个问题是什么意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM