0

编辑:我能够通过这段代码得到我需要的东西,它提取了与我的类型相关的伙伴类列表 - t 是我的非伙伴类的类型。

MetadataTypeAttribute[] metaAttr = (MetadataTypeAttribute[])t.GetCustomAttributes(typeof(MetadataTypeAttribute), true);

问题也在代码中的评论中 -

我有一个自定义属性应用于好友类(我首先使用的是 EF-DB)。但是,当我尝试获取 memberinfo 时,我看不到自定义属性。如何使用如下表达式提取此属性的值?

using System;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication1
{

// I have a custom attribute...
[System.AttributeUsage(System.AttributeTargets.Property)]
public class ExportNameAttribute : System.Attribute
{
    public string DisplayName;

    public ExportNameAttribute(string displayName)
    {
        DisplayName = displayName;
    }
}

// And I have a class with a metadata buddy class (to simulate how I need to do this with EF-DB first)
[MetadataType(typeof(AttributeTestMetaData))]
public partial class AttributeTest
{
    public string myAttribute { get; set; }
}

public class AttributeTestMetaData
{
    [ExportName("test")]
    public string myAttribute { get; set; }
}

// However, when I pull the member info for this property via an expression, I don't get the attribute back.
class Program
{
    static void Main(string[] args)
    {
        var mInfo = GetMemberInfo((AttributeTest at) => at.myAttribute); 
        Console.WriteLine(mInfo.CustomAttributes.Count().ToString()); // Outputs 0
    }

    public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)
    {
        var member = expression.Body as MemberExpression;
        if (member != null)
            return member.Member;

        throw new ArgumentException("Expression is not a member access", "expression");
    }
}

}

4

1 回答 1

0

我想出了如何做到这一点:

MetadataTypeAttribute[] metaAttr = (MetadataTypeAttribute[])t.GetCustomAttributes(typeof(MetadataTypeAttribute), true);

于 2015-09-25T19:20:54.140 回答