2014-10-01 26 views
0

編輯:我能夠通過此代碼得到我需要的東西,它拉出了與我的類型相關聯的好友類的列表-t是我的非好友類的類型。好友類MemberInfo不返回自定義屬性

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"); 
    } 
} 

}

回答

0

我想出如何做到這一點:

MetadataTypeAttribute [] metaAttr =(MetadataTypeAttribute [])t.GetCustomAttributes(typeof運算(MetadataTypeAttribute),TRUE);