gpt4 book ai didi

c# - 反射(reflection):框架行为与 GetRuntimeProperty 方法不一致

转载 作者:太空狗 更新时间:2023-10-29 19:44:15 28 4
gpt4 key购买 nike

在新的 .NET Framework 4.5 中使用反射时,我遇到了一个我发现非常意外的奇怪行为。命名空间 System.Reflection 提供了一些新的扩展方法来利用 Type 对象。其中两个是 GetRuntimeProperty(string name) 和 GetRuntimeProperties()。

现在假设您有一个具有内部属性的简单对象。

public class ObjectBase
{
protected int Id { get; set; }
public string Name { get; set; }
}

现在您尝试利用这种类型。

var properties = typeof(ObjectBase).GetRuntimeProperties();
// properties.Count = 2

var idProperty = typeof(ObjectBase).GetRuntimeProperty("Id");
var nameProperty = typeof(ObjectBase).GetRuntimeProperty("Name");
// idProperty = null
// nameProperty = System.String Name

正如预期的那样,properties 对象包含 Id 和 Name 属性定义的两个属性定义,nameProperty 包含 Name 属性定义。出乎意料的是 idProperty 对象为空...

来自 .NET Framework,我猜这是 Microsoft 架构师的意图,但我必须说这看起来不像是您真正期望发生的事情。我确实相信此类类似方法的行为应该相同,但似乎 GetRuntimeProperty 对公共(public)属性进行过滤,而 GetRuntimeProperties 不应用任何过滤器。

对于微软为什么决定那些相似的方法应该有不同的行为,有人有合理的解释吗?设计错误?

谢谢。

最佳答案

内部GetRuntimeProperty电话 Type.GetProperty(name)它搜索具有指定名称的公共(public)属性。属性(property)Id protected ,因此无法找到。

public static PropertyInfo GetRuntimeProperty(this Type type, string name)
{
CheckAndThrow(type);
return type.GetProperty(name);
}

另一方面GetRuntimeProperties返回公共(public)和非公共(public)属性

public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type)
{
CheckAndThrow(type);
return type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.Static | BindingFlags.Instance);
}

Explanation: GetRuntimeProperties目的是返回 IEnumerable<PropertyInfo>所有属性的集合,让您通过 LINQ 过滤该集合。您可以选择公共(public)、非公共(public)或任何其他类型的属性。使用 GetRuntimeProperty 返回的单个属性您不需要这种灵 active ,因此它仅限于大多数常见用途。

关于c# - 反射(reflection):框架行为与 GetRuntimeProperty 方法不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14003872/

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