2
mars
2007
Nouvel exemple d’utilisation des extensions methods
mars
2007
Quand on utilise la méthode GetCustomAttributes sur un MemberInfo, le type retourné est object[].
Cependant, cela peut être pénible quand on a précisé le type d’attribut dans les paramètres de GetCustomAttributes car il va falloir systèmatiquement caster le résultat de GetCustomAttributes afin de pouvoir utiliser des membres de notre attribut. Prenons un exemple :
class Program
{
static void Main(string[] args)
{
TestAttribute[] attributes = (TestAttribute[])(typeof(Test).GetProperty("Toto").GetCustomAttributes(typeof(TestAttribute), true));
Console.WriteLine(attributes[0].Value);
Console.ReadLine();
}
}
public class TestAttribute : Attribute
{
private string _value;
public string Value
{
get { return _value; }
set { _value = value; }
}
}
class Test
{
private string _toto = "";
[Test(Value="MyAttribute")]
public string Toto
{
get { return _toto; }
set { _toto = value; }
}
}
{
static void Main(string[] args)
{
TestAttribute[] attributes = (TestAttribute[])(typeof(Test).GetProperty("Toto").GetCustomAttributes(typeof(TestAttribute), true));
Console.WriteLine(attributes[0].Value);
Console.ReadLine();
}
}
public class TestAttribute : Attribute
{
private string _value;
public string Value
{
get { return _value; }
set { _value = value; }
}
}
class Test
{
private string _toto = "";
[Test(Value="MyAttribute")]
public string Toto
{
get { return _toto; }
set { _toto = value; }
}
}
Afin d’éviter de faire le cast, il est possible, avec C# 3.0, d’utiliser les extensions methods :
static class ExtensionMethods
{
public static T[] GetCustomAttributesTyped<T>(this MemberInfo memberInfo, bool inherit) where T:class
{
return (T[])(memberInfo.GetCustomAttributes(typeof(T), inherit));
}
}
{
public static T[] GetCustomAttributesTyped<T>(this MemberInfo memberInfo, bool inherit) where T:class
{
return (T[])(memberInfo.GetCustomAttributes(typeof(T), inherit));
}
}
Cette méthode s’utilise alors comme ceci :
TestAttribute[] attributes = typeof(Test).GetProperty("Toto").GetCustomAttributesTyped<TestAttribute>(true);