这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
这段代码:
Type.GetType("namespace.a.b.ClassName")
返回null。
我在使用:
using namespace.a.b;
类型是存在的,它在不同的类库中,我需要通过它的名字string来获取它。
当前回答
试试这个方法。
public static Type GetType(string typeName)
{
var type = Type.GetType(typeName);
if (type != null) return type;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
type = a.GetType(typeName);
if (type != null)
return type;
}
return null;
}
其他回答
type . gettype ("namespace.qualified.TypeName")仅在mscorlib.dll或当前正在执行的程序集中找到该类型时才有效。
如果这两种情况都不是真的,你将需要一个程序集限定的名称:
Type.GetType("namespace.qualified.TypeName, Assembly.Name")
对我来说,“+”是关键! 这是我的类(它是一个嵌套的):
namespace PortalServices
{
public class PortalManagement : WebService
{
public class Merchant
{}
}
}
这行代码起作用了:
Type type = Type.GetType("PortalServices.PortalManagement+Merchant");
如果程序集被引用并且Class可见:
typeof(namespace.a.b.ClassName)
GetType返回null,因为没有找到类型,使用typeof,编译器可以帮助你找出错误。
试试这个方法。
public static Type GetType(string typeName)
{
var type = Type.GetType(typeName);
if (type != null) return type;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
type = a.GetType(typeName);
if (type != null)
return type;
}
return null;
}
如果它是一个嵌套类型,您可能会忘记转换。到a +
不管怎样,typeof(T).FullName会告诉你应该说什么
编辑:顺便说一句,这些用法(我相信你知道)只是编译时对编译器的指令,因此不会对API调用的成功产生任何影响。(如果你有项目或装配的参考资料,可能会有潜在的影响-因此信息不是无用的,只是需要一些过滤…)