考虑以下代码:
public class MyClass
{
public MyClass(Type optionsClassType)
{
//A PropertyInfo[0] is returned here
var test1 = optionsClassType.GetProperties();
//Even using typeof
var test2 = typeof(MyClassOptions).GetProperties();
//Or BindingFlags
var test3 = typeof(MyClassOptions)
.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public);
}
}
public class MyClassOptions
{
public int MyProperty { get; set; }
}
我无法得到PropertyInfo[]
about MyClassOptions
, Type.GetProperties http://msdn.microsoft.com/en-us/library/system.type.getproperties.aspx始终返回一个空数组。首先,我认为这是 Xamarin.iOS 中的框架错误,但我在另一个针对同一框架的项目中测试了相同的代码,并且它工作得很好。
有人知道这可能的原因吗?
EDIT
感谢@Fabian Bigler 的回答,我明白了。
在我的项目中,即使 Linker 设置为适度行为,实例化MyClassOptions
不足以在运行时保留类定义。仅在实际使用实例(例如设置属性)之后,该类才会保留在我的构建中。
似乎链接器用虚拟对象替换了“未使用”的东西。
由于我将在这个项目中大量使用反射,因此我刚刚禁用了链接器,一切都恢复正常。
这段代码对我来说工作得很好:
namespace MyNameSpace
{
public class MyClass
{
public MyClass(Type optionsClassType)
{
//A PropertyInfo[0] is returned here
var test1 = optionsClassType.GetProperties();
//Even using typeof
var test2 = typeof(MyClassOptions).GetProperties();
//Or BindingFlags
var test3 = typeof(MyClassOptions).GetProperties
(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
}
}
public class MyClassOptions
{
public int MyProperty { get; set; }
}
}
Added BindingFlags.Instance
在代码中。欲了解更多信息,请查看这个帖子 https://stackoverflow.com/questions/1544979/net-reflection-getproperties-with-bindingflags-declaredonly.
然后从外部调用:
var options = new MyClassOptions();
options.MyProperty = 1234;
var t = options.GetType();
var c = new MyNameSpace.MyClass(t);
注意:小心汇编链接器
如果您在启用链接器的情况下进行构建,您可能需要在某个地方使用该类,这样它就不会在编译时被删除。有时,仅在代码中实例化类是不够的,链接器可能会检测到该实例从未使用过,并且无论如何都会将其删除。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)