2011-12-30 1 views
2

を回避することはできませんこれは、即時コンソールである:C#のリフレクションと属性:Bug?私はこの

prop.GetCustomAttributes(typeof(RequiredParameterAttribute),true) 

{BridgeStack.DataContracts.RequiredParameterAttribute [0]}

prop.GetCustomAttributes(typeof(RequiredParameterAttribute),true).Cast<RequiredParameterAttribute>() 

{BridgeStack.DataContracts .RequiredParameterAttribute [0]} [BridgeStack.DataContracts.RequiredParameterAttribute []]:{BridgeStack.DataContracts.RequiredParameterAttribute [0]}

prop.GetCustomAttributes(typeof(RequiredParameterAttribute),true).Cast<RequiredParameterAttribute>().Any() 

私は、アプリケーションで同じ結果を得ます。

propは中Siteです:

順番に
public class AnswerCollectionQuery : IPagedQuery, ISiteQuery, ISortableQuery, IOrderableQuery, IFilteredQuery 
{ 
    public int? Page { get; set; } 
    public int? PageSize { get; set; } 
    public string Site { get; set; } 

    [AllowedSortValues(QuerySortEnum.Activity, QuerySortEnum.Creation, QuerySortEnum.Votes)] 
    public QuerySortEnum? Sort { get; set; } 

    public object Min { get; set; } 
    public object Max { get; set; } 
    public DateTime? FromDate { get; set; } 
    public DateTime? ToDate { get; set; } 

    public QueryOrderEnum? Order { get; set; } 

    public string Filter { get; set; } 
} 

Siteぎこちない部分は、コンソールが属性を示すことであるISiteQuery

public interface ISiteQuery : IQuery 
{ 
    [RequiredParameter] 
    string Site { get; set; } 
} 

から来て、「私はそれをキャストすることができますが、私はすることができますそれをすべて取得すると、列挙の長さがゼロになるので、.Any()も失敗します。.FirstOrDefault()は、null、を返します。スローなど

このタイプの動作についての説明はありますか?

PD:Siteを具体的なクラスの[RequiredAttribute]で飾っても、これはうまくいきます。しかし、私はこのインターフェースの一部を作りたがっていました。明快ため

更新:

propはここから正確に来る:

public static IEnumerable<PropertyInfo> GetAllProperiesOfObject(object o) 
    { 
     const BindingFlags flags = BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance; 
     PropertyInfo[] list = o.GetType().GetProperties(flags); 

     return list; 
    } 

foreach (PropertyInfo prop in Utility.GetAllProperiesOfObject(entity))

これはpropがゼロで、それからですSite

+0

小道具とは何ですか?それはどこから来たの? –

+0

これらの詳細を更新しました。 – bevacqua

+0

http://stackoverflow.com/questions/540749/can-a-c-sharp-class-inherit-attributes-from-its-interface クラスはインターフェイスから属性を継承しません。 –

答えて

2

になったときのためのケースですあなたにゼロlenを返していますgth型付き配列です。つまり、属性はありません。 Attribute.IsDefined(falseを返す)でこれを見ることもできます。

暗黙インターフェイスの実装を使用する場合、クラスのpublicプロパティは自動的に満たしているインターフェイスから属性を取得しません。インターフェイス上の属性を確認するには、使用する必要があります

typeof(ITheInterface).GetProperties() 

インターフェイスのサイトプロパティは、クラスのサイトプロパティとは無関係です。クラスのプロパティに属性が必要な場合は、属性を明示的に追加します。

関連する問題