正如标题所述,在使用反射时,如何测试属性是否已声明为dynamic
?
不幸的是,在我的情况下,使用!pi.PropertyType.IsValueType
不够具体。我发现的唯一方法是浏览pi.CustomAttributes
数组并测试它是否包含AttributeType
为DynamicAttribute
的项目。有没有[[更好的方法可以实现这个目标?
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)); } }
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]
属性的存在。