好友类MemberInfo不返回自定义属性

时间:2014-10-01 22:29:59

标签: c# entity-framework reflection buddy-class

编辑:我能够通过这段代码得到我所需要的东西,它提取了与我的类型相关的伙伴类列表 - 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");
    }
}

}

1 个答案:

答案 0 :(得分:0)

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

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