gpt4 book ai didi

c# - 如何确定属性是否是具有反射的自动实现属性?

转载 作者:IT王子 更新时间:2023-10-29 04:19:05 26 4
gpt4 key购买 nike

所以在我的例子中,我正在使用反射发现类的结构。我需要能够查明某个属性是否是 PropertyInfo 对象自动实现的属性。我假设反射 API 不会公开此类功能,因为自动属性依赖于 C#,但是否有任何解决方法来获取此信息?

最佳答案

您可以检查 getset 方法是否标有 CompilerGenerated 属性。然后,您可以将其与查找标有 CompilerGenerated 属性且包含属性名称和字符串 "BackingField" 的私有(private)字段相结合。

也许:

public static bool MightBeCouldBeMaybeAutoGeneratedInstanceProperty(
this PropertyInfo info
) {
bool mightBe = info.GetGetMethod()
.GetCustomAttributes(
typeof(CompilerGeneratedAttribute),
true
)
.Any();
if (!mightBe) {
return false;
}


bool maybe = info.DeclaringType
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.Name.Contains(info.Name))
.Where(f => f.Name.Contains("BackingField"))
.Where(
f => f.GetCustomAttributes(
typeof(CompilerGeneratedAttribute),
true
).Any()
)
.Any();

return maybe;
}

它不是万无一失的,非常脆弱,可能无法移植到 Mono。

关于c# - 如何确定属性是否是具有反射的自动实现属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2210309/

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