Created
October 23, 2020 03:44
-
-
Save Lvcios/2e460783e9b72e628b7f6da440f2a4ac to your computer and use it in GitHub Desktop.
How to use custom property attributes and get their values in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reflection; | |
namespace CustomPropertyAttributes | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var properties = typeof(ClientsExcelReport).GetProperties(); | |
foreach(var prop in properties) | |
{ | |
Console.WriteLine($"Prop name: {prop.Name}"); | |
if(Attribute.IsDefined(prop, typeof(ExcelColumnNameAttribute))) | |
Console.WriteLine(prop.GetCustomAttribute<ExcelColumnNameAttribute>().ColumnName); | |
if (Attribute.IsDefined(prop, typeof(ExcelColumnCommentAttribute))) | |
Console.WriteLine(prop.GetCustomAttribute<ExcelColumnCommentAttribute>().Comment); | |
Console.WriteLine("**************"); | |
} | |
} | |
} | |
class ClientsExcelReport | |
{ | |
[ExcelColumnName("Nombre del cliente")] | |
[ExcelColumnComment("Algun comentario tonto sobre la columna")] | |
public string ClientName { get; set; } | |
[ExcelColumnName("País")] | |
public string ClientCountry { get; set; } | |
[ExcelColumnName("Edad")] | |
public string Age { get; set; } | |
public string Status { get; set; } | |
} | |
public class ExcelColumnNameAttribute : Attribute | |
{ | |
public ExcelColumnNameAttribute(string columnName) | |
{ | |
ColumnName = columnName; | |
} | |
public string ColumnName { get; } | |
} | |
public class ExcelColumnCommentAttribute : Attribute | |
{ | |
public ExcelColumnCommentAttribute(string comment) | |
{ | |
Comment = comment; | |
} | |
public string Comment { get; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment