检索我的客户端定义的自定义属性值

本文关键字:自定义属性 定义 我的 客户端 检索 | 更新日期: 2023-09-27 18:31:16

我试图使用c#的自定义属性。

作为其中的一部分,请考虑以下场景:我有我的客户端类,它为我提供了一个要哈希的字符串,并使用自定义属性指定哈希算法。

我能够解决这个问题,但在如何检索自定义属性值时卡住了。

class HashAlgorithmAttribute : Attribute
{
    private string hashAlgorithm;
    public HashAlgorithmAttribute(string hashChoice)
    {
        this.hashAlgorithm= hashChoice;
    }
}
[HashAlgorithm("XTEA")]
class ClientClass
{
    public static string GetstringToBeHashed()
    {
        return "testString";
    }
}
class ServerClass
{
    public void GetHashingAlgorithm()
    {
        var stringToBeHashed = ClientClass.GetstringToBeHashed();
        ///object[] hashingMethod = typeof(HashAlgorithm).GetCustomAttributes(typeof(HashAlgorithm), false);
    }
}

检索我的客户端定义的自定义属性值

使用属性类的模拟示例:

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class HashAlgorithmAttribute : Attribute
{
    readonly string algorithm;
    public HashAlgorithmAttribute(string algorithm)
    {
        this.algorithm = algorithm;
    }
    public string Algorithm
    {
        get { return algorithm; }
    }
}

和测试类:

[HashAlgorithm("XTEA")]
class Test
{
}

要获取值,请执行以下操作:

var attribute = typeof(Test).GetCustomAttributes(true)
     .FirstOrDefault(a => a.GetType() == typeof(HashAlgorithmAttribute));
var algorithm = "";
if (attribute != null)
{
    algorithm = ((HashAlgorithmAttribute)attribute).Algorithm;
}
Console.WriteLine(algorithm); //XTEA