C# 给定一个自定义类和自定义属性,如何从基类中找到类的属性

标签 c# reflection

给定以下类(class)

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

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

    }


}

如何从基类中找到 KeyField 属性的值。

最佳答案

我想你在构建阶段需要它

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
}

相同的代码在类中的其他函数中的工作方式相同

关于C# 给定一个自定义类和自定义属性,如何从基类中找到类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46409526/

相关文章:

C# 运行时类创建

c# - 使用属性减少枚举到枚举的映射以及枚举/常量到 Action 切换语句

C# 反射 - 我可以检查一个方法是否调用另一个方法吗

c# - asp.net 身份 - SetPasswordHashAsync

c# - RabbitMQ 中的并发

c# - 如何以编程方式修改 app.config 中的 assemblyBinding?

reflection - C# - 在运行时确定属性是 Type 还是 Object 实例?

c# - 用于 webm 视频转换的 API

c# - 有没有办法检查 TextWriter 是否关闭?

objective-c - 具有底部反射的 UIImage