Last active
December 13, 2015 21:18
-
-
Save cz75hiro/4976174 to your computer and use it in GitHub Desktop.
ラムダ式で指定したプロパティの属性を取得するサンプル
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
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