【问题标题】:C# .NET CORE how to get the value of a custom attribute?C# .NET CORE 如何获取自定义属性的值?
【发布时间】:2017-03-10 07:13:28
【问题描述】:

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

[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 的值?

var config = new KeyVaultConfiguration();

// var authClientIdIsEncrypted = ??

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

【问题讨论】:

    标签: c# .net-core custom-attributes


    【解决方案1】:

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

    这样的东西应该适合你:

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

    在你的情况下

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

    【讨论】:

    • 链接已失效。
    猜你喜欢
    • 2020-08-28
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2019-11-12
    • 2011-07-03
    • 1970-01-01
    相关资源
    最近更新 更多