Skip to content

Instantly share code, notes, and snippets.

@cz75hiro
Last active December 13, 2015 21:18
Show Gist options
  • Save cz75hiro/4976174 to your computer and use it in GitHub Desktop.
Save cz75hiro/4976174 to your computer and use it in GitHub Desktop.
ラムダ式で指定したプロパティの属性を取得するサンプル
static class Program
{
static void Main(string[] args)
{
var test = new Test();
Console.WriteLine(test.GetFugaString(x => x.TestProperty));
Console.Read();
}
public static string GetFugaString<TSource, TSelector>(this TSource source, Expression<Func<TSource, TSelector>> propertyExpression) where TSource : class
{
var attrs = GetAttributes(propertyExpression);
foreach(var item in attrs)
{
HogeAttribute attr;
if(item is HogeAttribute)
{
attr = item as HogeAttribute;
return attr.Fuga;
}
}
return "";
}
private static object[] GetAttributes<TSource, TSelector>(Expression<Func<TSource, TSelector>> propertyExpression)
{
if(propertyExpression == null) throw new ArgumentNullException("propertyExpression");
if(!(propertyExpression.Body is MemberExpression)) throw new NotSupportedException("このメソッドでは x => x.プロパティ の形式のラムダ式以外許可されません");
var memberExpression = (MemberExpression)propertyExpression.Body;
return memberExpression.Member.GetCustomAttributes(false);
}
}
public class Test
{
[Hoge(Fuga = "ふが~")]
public string TestProperty { get; set; }
}
public class HogeAttribute : Attribute
{
public string Fuga { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment