【问题标题】:Buddy Class MemberInfo not returning custom attributesBuddy Class MemberInfo 不返回自定义属性
【发布时间】:2014-10-01 22:29:58
【问题描述】:

编辑:我能够通过此代码获得所需的内容,该代码提取了与我的类型相关联的伙伴类列表 - 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");
    }
}

}

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2011-09-12
      • 2021-05-14
      相关资源
      最近更新 更多