-
Notifications
You must be signed in to change notification settings - Fork 2
/
Helpers.cs
52 lines (47 loc) · 1.91 KB
/
Helpers.cs
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
using Supabase.Core.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Supabase.Core
{
/// <summary>
/// Shortcut Methods, mostly focused on getting attributes from class properties and enums.
/// </summary>
public static class Helpers
{
/// <summary>
/// Returns the current value from a given class property
/// </summary>
/// <param name="obj"></param>
/// <param name="propName"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetPropertyValue<T>(object obj, string propName) => (T)obj.GetType().GetProperty(propName).GetValue(obj, null);
/// <summary>
/// Returns a cast Custom Attribute from a given object.
/// </summary>
/// <param name="obj"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetCustomAttribute<T>(object obj) where T : Attribute => (T)Attribute.GetCustomAttribute(obj.GetType(), typeof(T));
/// <summary>
/// Returns a cast Custom Attribute from a given type.
/// </summary>
/// <param name="type"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetCustomAttribute<T>(Type type) where T : Attribute => (T)Attribute.GetCustomAttribute(type, typeof(T));
/// <summary>
/// Shortcut method for accessing a `MapTo` attribute, combined with an Enum.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static MapToAttribute GetMappedToAttr(Enum obj)
{
var type = obj.GetType();
var name = Enum.GetName(type, obj);
return type.GetField(name).GetCustomAttributes(false).OfType<MapToAttribute>().SingleOrDefault();
}
}
}