2017-09-25 50 views
2

找到一個類的屬性考慮下面的類C#屬性如何從基類

[KeyField("dap_name")] 
public class nhs_acquisition_profile 
    : DALObject 
    , IDisposable 
{ 
    public nhs_acquisition_profile() 
     : base() 
    { 
    } 

    public nhs_acquisition_profile(String ConnectionString) 
     : base(ConnectionString) 
    { 

    } 


} 

我怎麼能找到的關鍵字段屬性的值,但是從基類。

+1

'this.GetType()'可能是你的朋友,如果我正確理解你的場景。如果沒有,它可以用一些示例代碼來更好地說明您的問題。 –

+1

你可以對DALObject類型使用relection來查找它的繼承者,然後獲得這些屬性的自定義屬性 - 但是你仍然需要知道你在找哪一個屬性 - 所以這可能不是你想要的如果由於某種原因,您需要通過基本類型來完成此操作。 – thisextendsthat

回答

4

我想你需要它在施工階段

public DALObject() // base constructor 
{ 
    var fieldAttr = GetType() // real type 
     .GetCustomAttributes(typeof(KeyFieldAttribute), true) // look for attribute 
     .FirstOrDefault(); // can take more than one, it's an example 
    var resultField = (fieldAttr as KeyFieldAttribute)?.Field; // cast and use 
} 

相同的代碼將工作在其它功能相同的類