C# .NET CORE 如何获取自定义属性的值? [英] C# .NET CORE how to get the value of a custom attribute?
问题描述
我有一个自定义属性类,定义如下.
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;
}
}
}
我将上述属性应用到另一个类中,如下所示.
I applied the above attribute to another class as follows.
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?
推荐答案
Add using 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屋!