如何测试 属性 是否被声明为 "dynamic"?

How to test if a property has been declared as "dynamic"?

正如标题所说,使用反射时,如何测试属性是否被声明为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));
    }
}

如果您将代码放在 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] 属性是否存在。