Skip to content

Instantly share code, notes, and snippets.

@M-Zuber
Last active December 20, 2019 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save M-Zuber/e2c882e95fefacfd80ccc1a7ae406c90 to your computer and use it in GitHub Desktop.
Save M-Zuber/e2c882e95fefacfd80ccc1a7ae406c90 to your computer and use it in GitHub Desktop.
Use case for generic attributes in c#
using System;
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class LoggerAttribute<T> : Attribute
{
readonly string _template;
public LoggerAttribute(string positionalString)
{
_template = positionalString;
}
public string PositionalString
{
get { return _template; }
}
}
[Logger<InsertFoo>($"Inserting {Id} -> {Name}")]
class InsertFoo
{
public int Id { get; set; }
public string Name { get; set; }
}
using System;
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class LoggerAttribute<T> : Attribute
{
readonly Func<T, string> _template;
public LoggerAttribute(Func<T, string> positionalString)
{
_template = positionalString;
}
public Func<T, string> PositionalString
{
get { return _template; }
}
}
[Logger<InsertFoo>(f => $"Inserting {f.Id} -> {f.Name}")]
class InsertFoo
{
public int Id { get; set; }
public string Name { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment