2017-09-25 46 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 
} 

相同的代码将工作在其它功能相同的类