C#.NET CORE如何获取自定义属性的值?

Sam*_*evx 6 c# custom-attributes .net-core

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

[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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我将以上属性应用于另一个类,如下所示.

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

    public string AuthClientCertThumbprint { get; set; } = "";
}
Run Code Online (Sandbox Code Playgroud)

如何在属性AuthClientId上获取Encrypted = True的值?

var config = new KeyVaultConfiguration();

// var authClientIdIsEncrypted = ??
Run Code Online (Sandbox Code Playgroud)

在.NET Framework中,这很容易.在.NET CORE中,我认为这是可能的,但我没有看到任何文档.我相信你需要使用System.Reflection但究竟如何?

Set*_*Set 15

添加using System.Reflection然后您可以使用CustomAttributeExtensions.cs中的扩展方法.

这样的事情对你有用:

typeof(<class name>).GetTypeInfo()
      .GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
Run Code Online (Sandbox Code Playgroud)

在你的情况下

typeof(KeyVaultConfiguration).GetTypeInfo()
      .GetProperty("AuthClientId").GetCustomAttribute<EncryptedAttribute>();
Run Code Online (Sandbox Code Playgroud)

  • 链接已死。 (3认同)