如何测试属性是否已声明为“动态”?

问题描述 投票:0回答:1

正如标题所述,在使用反射时,如何测试属性是否已声明为dynamic

不幸的是,在我的情况下,使用!pi.PropertyType.IsValueType不够具体。我发现的唯一方法是浏览pi.CustomAttributes数组并测试它是否包含AttributeTypeDynamicAttribute的项目。有没有[[更好的方法可以实现这个目标?

public class SomeType { public dynamic SomeProp { get; set; } } // ... foreach (var pi in typeof(SomeType).GetProperties()) { if (pi.PropertyType == typeof(string)) { } // okay if (pi.PropertyType == typeof(object)) { } // okay if (pi.PropertyType == typeof(dynamic)) { } // The typeof operator cannot be used on the dynamic type }

感谢您的答复。这是我解决的方法:

public static class ReflectionExtensions { public static bool IsDynamic(this PropertyInfo propertyInfo) { return propertyInfo.CustomAttributes.Any(p => p.AttributeType == typeof(DynamicAttribute)); } }

c# system.reflection
1个回答
1
投票
如果将代码放入SharpLib.io,则可以在后台看到代码发生了什么。

using System; public class C { public dynamic SomeProp { get; set; } public void M() { SomeProp = 3; } }

被转换为(为了可读性删除了一些东西:

using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; public class C { [Dynamic] private object <SomeProp>k__BackingField; [Dynamic] public object SomeProp { [return: Dynamic] get { return <SomeProp>k__BackingField; } [param: Dynamic] set { <SomeProp>k__BackingField = value; } } public void M() { SomeProp = 3; } }

SomeProp属性只是.Net运行时的普通object。附加[Dynamic]属性。

无法测试动态类型,因为它不是SomeProp的类型。您应该测试[Dynamic]属性的存在。

© www.soinside.com 2019 - 2024. All rights reserved.