我有程序集 A 引用程序集 B。它们位于同一目录中。
Type[] types = null;
try
{
Assembly a = Assembly.Load("A.dll");
types = a.GetTypes(); // loads B implicitly.
}
catch(ReflectionTypeLoadException ex)
{
types = ex.Types.Where(x=>x!=null);
}
Run Code Online (Sandbox Code Playgroud)
如何防止 B 被加载?我希望 GetTypes() 像 B 不可用一样运行,并且只返回可用类型和 null 表示不可用,以便我可以执行
ex.Types.where(x=>x!=null);
我想在调用 Assembly.GetTypes() 时使用How to prevent ReflectionTypeLoadException 中的技巧
这样我只能得到不依赖于 B 的类型并使用它们。
更新:
我在反射和正常上下文中都加载了 A 。我使用反射上下文 A 来调用 GetTypes()。从反射上下文程序集获取类型后,我遇到了另一个问题。当我调用 Type.GetCustomAttributes() 时,收到以下异常
反映通过 ReflectionOnlyGetType(参见 Assembly.ReflectionOnly)加载的类型的自定义属性是非法的——改用 CustomAttributeData。
我通过从普通上下文程序集中获取相同类型来解决它。
//... code omited for brevity
Type reflectionType = reflectionAssembly.GetTypes()[0];
//... code omited for …Run Code Online (Sandbox Code Playgroud) 以下代码在VS 2012中编译,但在VS 2013中编译
std::ofstream stm;
if(stm != NULL)
{
}
Run Code Online (Sandbox Code Playgroud)
在VS 2013中,您收到此编译错误:
二进制'!='找不到运算符,它接受类型为'std :: ofstream'的左手操作数(或者没有可接受的转换)
我查看了标题,<xiobase>然后发现了以下内容:
VS2012
ios_base::operator void *() const;
Run Code Online (Sandbox Code Playgroud)
VS2013
operator void *() const 已删除,并添加了显式操作符bool:
ios_base::explicit operator bool() const;
Run Code Online (Sandbox Code Playgroud)
现在我的问题:
void*或explicit从运算符bool()中删除的条件编译指令.PS:gcc 4.9.0还有operator void*() const.所以它不会有这个问题.
更新:
为了使我的遗留代码编译,我按照建议实现了以下重载:
#include <xiosbase>
bool operator==(const std::basic_ios<char, char_traits<char>> &stm, int null_val)
{
return static_cast<bool>(stm) == null_val;
}
bool operator==(int null_val, const std::basic_ios<char, char_traits<char>> &stm)
{
return operator==(stm, null_val);
}
bool operator!=(int null_val, …Run Code Online (Sandbox Code Playgroud)