如何确定一个属性是否是带有反射的自动实现的属性?

编程入门 行业动态 更新时间:2024-10-13 18:19:41
本文介绍了如何确定一个属性是否是带有反射的自动实现的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

So in my case i am doing discovery of the structure of a class using reflection. I need to be able to find out if a property is an auto-implemented property by the PropertyInfo object. I assume that the reflection API does not expose such functionality because auto-properties are C# dependent, but is there any workaround to get this information?

推荐答案

您可以检查 get 或 set 方法是否标有 CompilerGenerated 属性.然后,您可以将其与查找标记有 CompilerGenerated 属性的私有字段结合使用,该属性包含属性名称和字符串 "BackingField".

You could check to see if the get or set method is marked with the CompilerGenerated attribute. You could then combine that with looking for a private field that is marked with the CompilerGenerated attribute containing the name of the property and the string "BackingField".

也许:

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 等平台上.

It's not fool proof, quite brittle and probably not portable to, say, Mono.

更多推荐

如何确定一个属性是否是带有反射的自动实现的属性?

本文发布于:2023-06-08 21:31:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589419.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   反射

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!