2017-03-09 172 views
4

我有一個自定義的屬性類定義如下。C#.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; 
     } 
    } 
} 

我將上述屬性應用於另一個類,如下所示。

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,但究竟如何?

回答

9

添加using System.Reflection然後您可以使用CustomAttributeExtensions.cs的擴展方法。

像這樣的東西應該爲你工作:感謝

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

你的情況

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

是啊,這是它:) – SamDevx

+0

幫助了很多 - 謝謝! – xFight

相關問題