C#.NET CORE如何获取自定义属性的值? [英] C# .NET CORE how to get the value of a custom attribute?

查看:785
本文介绍了C#.NET CORE如何获取自定义属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义如下的自定义属性类。

I have a custom attribute class defined as follows.

[AttributeUsage(AttributeTargets.Property, Inherited = false)]
internal class EncryptedAttribute : System.Attribute
{
    private bool _encrypted;
    public EncryptedAttribute(bool encrypted)
    {
        _encrypted = encrypted;
    }

    public virtual bool Encrypted
    {
        get
        {
            return _encrypted;
        }
    }
}

我将上述属性应用于

public class KeyVaultConfiguration
{
    [Encrypted(true)]
    public string AuthClientId { get; set; } = "";

    public string AuthClientCertThumbprint { get; set; } = "";
}

如何获得AuthClientId属性的Encrypted = True值?

How do I get the value of Encrypted=True on property AuthClientId?

var config = new KeyVaultConfiguration();

// var authClientIdIsEncrypted = ??

在.NET Framework中,这很容易。在.NET CORE中,我认为这是可能的,但是我看不到任何文档。我相信您需要使用System.Reflection,但到底要使用什么方法?

In .NET Framework, this was easy. In .NET CORE, I think this is possible but I don't see any documentation. I believe you need to use System.Reflection but exactly how?

推荐答案

使用System.Reflection添加 ,然后您可以使用 CustomAttributeExtensions.cs

Add using System.Reflection and then you may use extension methods from CustomAttributeExtensions.cs.

类似的东西应该对您有用:

Something like this should work for you:

typeof(<class name>).GetTypeInfo()
      .GetProperty(<property name>).GetCustomAttribute<YourAttribute>();

在您的情况下

typeof(KeyVaultConfiguration).GetTypeInfo()
      .GetProperty("AuthClientId").GetCustomAttribute<EncryptedAttribute>();

这篇关于C#.NET CORE如何获取自定义属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆