所以就我而言,我正在使用反射来发现类的结构.我需要能够确定某个属性是否是 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.
更多推荐
如何确定一个属性是否是带有反射的自动实现的属性?
发布评论