2017-08-17 15 views
-2

下面的代碼行應該給我的屬性列表定義我的屬性,但它沒有給我任何結果。爲什麼Attribute.IsDefined沒有檢查我的Myproperty的自定義屬性列表

var props = typeof(D).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(MYAttribute))); 

樣品財產

[Serializable] 
    [Table()] 
    public class MYClass : IMyInterface 
    { 
     [Column()] 
     [MyAttribute(HeaderFields.MyValue)] 
     public string MyProp { get; set; } 
    } 

當我調試,我能夠看到屬性包含自定義屬性列表中的屬性。我在這裏錯過了什麼?

enter image description here

編輯

我想在下面的函數來獲得屬性

private static void MyFunction<D>(D MyObj) 
    where D : IMyInterface        
{ 
var props = typeof(D).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(MYAttribute))); 
} 

編輯

真正的問題是Visual Studio中沒有給予任何衝突錯誤/警告是在不同名稱空間中使用相同名稱定義的屬性。

回答

0

假設你已經安排如下代碼:

[Serializable] 
[Table("FooTable")] 
public class MYClass : IMyInterface 
{ 
    [Column("FooColumn")] 
    [My(HeaderFields.MyValue)] 
    public string MyProp { get; set; } 
} 

public class MyAttribute : Attribute 
{ 
    public MyAttribute(object myValue) { } 
} 

public enum HeaderFields 
{ 
    MyValue, 
    MyAnotherValue 
} 

public interface IMyInterface 
{ 
    string MyProp { get; set; } 
} 

現在,您可以得到所有已定義的屬性MyAttribute你的屬性,以下列方式:

using System; 
using System.Linq; 
using System.Reflection; 

class Program 
{ 
    public static void Main(string[] args) 
    { 
     var props = typeof(MYClass).GetProperties().Where(prop => prop.IsDefined(typeof(MyAttribute), false)); 

     foreach (PropertyInfo propertyInfo in props) 
     { 
      string newLine = Environment.NewLine; 

      Console.Out.WriteLine($"propertyInfo:" + newLine + 
            $"\tName = {propertyInfo.Name}," + newLine + 
            $"\Format = {propertyInfo}" + newLine); 
     } 
    } 
} 

鑑於提供的例子,你應該得到這樣的結果:

的PropertyInfo:

名稱= MyProp,

格式= System.String MyProp

+0

我想,我錯過了編碼,可能造成這個問題的一部分。讓我編輯我的問題。作爲你的改變prop.IsDefined(typeof(MyAttribute),false)也沒有給我結果。 – Hybridzz

+0

我想我應該使用typeof(D).UnderlyingSystemType.GetProperties()。嘗試一下。 – Hybridzz

+1

其實我的問題是,因爲在不同的命名空間中定義了2個屬性,Visual Studio沒有給我任何衝突錯誤。感謝您的回答。 – Hybridzz

相關問題