GetCustomAttribute在.NET 4.0中等效

时间:2015-07-28 06:16:10

标签: c# .net reflection .net-4.0

我正在使用来自here

的实体框架审计跟踪的示例项目

问题是我们已在项目中使用.NET 4.0,但此示例使用的是.NET 4.5。

有人可以告诉我.NET 4中GetCustomAttribute的等价物, 以下是我的代码:

    private static string ColumnNameFactory(this Type type, string propertyName)
    {
        string columnName = propertyName;
        Type entityType = type.GetEntityType();
        var columnAttribute = entityType.GetProperty(propertyName).GetCustomAttribute<ColumnAttribute>(false);
        if (columnAttribute != null && !string.IsNullOrEmpty(columnAttribute.Name))
        {
            columnName = columnAttribute.Name;
        }
        return columnName;
    }

在此代码中:GetCustomAttribute无法识别。

1 个答案:

答案 0 :(得分:6)

MemberInfo.GetCustomAttribute<T>()属于CustomAttributeExtensions扩展程序类,其中包含Attribute.GetCustomAttribute()Attribute.GetCustomAttributes()的非常薄的包装器。这些包装器将返回的Attribute强制转换为期望的属性类型。请参阅此处的参考来源:https://referencesource.microsoft.com/#mscorlib/system/reflection/CustomAttributeExtensions.cs

相关问题