【问题标题】:Retrieving the custom attribute value defined by my client检索我的客户定义的自定义属性值
【发布时间】:2025-12-26 01:55:06
【问题描述】:

我正在尝试使用 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);

    }
}

【问题讨论】:

  • @OP 请查看我的回答

标签: c# .net custom-attributes


【解决方案1】:

使用您的属性类的模拟示例:

[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

【讨论】: