请考虑以下代码:
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; }
}
我无法获取关于MyClassOptions
的PropertyInfo[]
,Type.GetProperties
总是返回一个空数组。起初我认为这是Xamarin.iOS中的框架错误,但我在针对相同框架的另一个项目中测试了相同的代码,结果正常运行。
有人知道可能的原因吗?
编辑
感谢@Fabian Bigler的答案,我明白了。
在我的项目中,即使链接器设置为适度的行为,实例化MyClassOptions
还不足以在运行时保留类定义。只有在实际使用实例(例如设置属性)之后,该类才会保留在我的构建中。
似乎链接器用虚拟对象替换了“未使用”的东西。 由于在这个项目中我将经常使用反射,所以我刚刚禁用了链接器,现在一切都正常了。