0

編集: このコードを介して必要なものを取得できました。このコードは、私のタイプに関連付けられたバディ クラスのリストを取得しました。t は、バディではないクラスのタイプです。

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

質問はコードのコメントにもあります-

バディ クラスに適用されているカスタム属性があります (最初に EF-DB を使用しています)。ただし、メンバー情報を取得しようとすると、カスタム属性が表示されません。以下のような式を使用して、この属性の値を取得するにはどうすればよいですか?

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 に答える