通过提供类名称作为字符串来获取引用程序集中的类型? [英] Get type in referenced assembly by supplying class name as string?
问题描述
这些是类似的问题:方法:在运行时使用Silverlight中的字符串从引用的程序集中加载类型,,但没有一个答案有效。
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.Car
或 MyFramework.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屋!