简体   繁体   中英

C# Given a custom class and custom attribute how can you find the attributes of a class from the base class

Given the following class

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

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

    }


}

How could I find the value of the KeyField Attribute but from the base class.

I suppose you need it in a construction phase

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
}

The same code will works the same in other functions in the class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM