gpt4 book ai didi

c# - Type.GetProperties 什么都不返回

转载 作者:太空狗 更新时间:2023-10-29 21:22:55 26 4
gpt4 key购买 nike

考虑以下代码:

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; }
}

我无法获取关于 MyClassOptionsPropertyInfo[]Type.GetProperties总是返回一个空数组。起初我以为这是 Xamarin.iOS 中的一个框架错误,但我在另一个针对相同框架的项目中测试了相同的代码并且它工作得很好。

有人知道这可能的原因吗?

编辑

感谢@Fabian Bigler 的回答,我明白了。在我的项目中,即使将链接器设置为中等行为,实例化 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; }
}
}

在代码中添加了 BindingFlags.Instance。有关更多信息,请查看 this post .


然后从外部调用:

var options = new MyClassOptions();
options.MyProperty = 1234;
var t = options.GetType();
var c = new MyNameSpace.MyClass(t);

注意:小心汇编链接器

如果您在启用链接器的情况下进行构建,您可能需要在某处使用该类,因此它不会在编译时被扯掉。有时,仅在代码中实例化类是不够的,链接器可能会检测到该实例从未被使用过,并且无论如何都会将其删除。

关于c# - Type.GetProperties 什么都不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17091115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com