Buddy Class MemberInfo未返回自定义属性



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

}

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

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

相关内容

  • 没有找到相关文章

最新更新