~ruther/NosSmooth

ref: 046116fdda4f2f5c9a70e10f89e8d7211d52dbb8 NosSmooth/Core/NosSmooth.PacketSerializersGenerator/Extensions/AttributeInfoExtensions.cs -rw-r--r-- 1.9 KiB
046116fd — František Boháček feat: move move packet to entities namespace 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
//  AttributeInfoExtensions.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Diagnostics;
using NosSmooth.PacketSerializersGenerator.Data;

namespace NosSmooth.PacketSerializersGenerator.Extensions;

/// <summary>
/// Extension methods for <see cref="AttributeInfo"/>.
/// </summary>
public static class AttributeInfoExtensions
{
    /// <summary>
    /// Get value of a named parameter.
    /// </summary>
    /// <param name="attributeInfo">The attribute information.</param>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="default">The default value to return if not found.</param>
    /// <typeparam name="TValue">The value type.</typeparam>
    /// <returns>The value of the attribute.</returns>
    public static TValue? GetNamedValue<TValue>(this AttributeInfo attributeInfo, string name, TValue? @default)
    {
        if (attributeInfo.NamedAttributeArguments.TryGetValue(name, out var value))
        {
            if (typeof(TValue) == typeof(string))
            {
                return (TValue?)(object?)value?.ToString();
            }

            return (TValue?)value;
        }

        return @default;
    }

    /// <summary>
    /// Get value of a named parameter.
    /// </summary>
    /// <param name="attributeInfo">The attribute information.</param>
    /// <param name="index">The index of the parameter.</param>
    /// <typeparam name="TValue">The value type.</typeparam>
    /// <returns>The value of the attribute.</returns>
    public static TValue? GetIndexedValue<TValue>(this AttributeInfo attributeInfo, int index)
    {
        var value = attributeInfo.IndexedAttributeArguments[index];

        if (typeof(TValue) == typeof(string))
        {
            return (TValue?)(object?)value?.ToString();
        }

        return (TValue?)value;
    }
}
Do not follow this link