kbt*_*tzr 6 c# reflection linker xamarin.ios
请考虑以下代码:
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; }
}
Run Code Online (Sandbox Code Playgroud)
我无法获得PropertyInfo[]
约MyClassOptions
,Type.GetProperties
总是返回一个空数组.首先我认为这是Xamarin.iOS中的一个框架错误,但是我在另一个针对相同框架的项目中测试了相同的代码并且它工作得很好.
有人知道可能的原因吗?
编辑
感谢@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; }
}
}
Run Code Online (Sandbox Code Playgroud)
BindingFlags.Instance
在代码中添加.有关详细信息,请查看此文章.
然后从外面打电话:
var options = new MyClassOptions();
options.MyProperty = 1234;
var t = options.GetType();
var c = new MyNameSpace.MyClass(t);
Run Code Online (Sandbox Code Playgroud)
如果您在启用链接器的情况下构建,则可能需要在某处使用该类,因此在编译时不会被删除.有时,仅在代码中实例化类是不够的,链接器可能会检测到实例从未使用过,并且无论如何都会将其删除.
归档时间: |
|
查看次数: |
10728 次 |
最近记录: |