Created
March 27, 2018 09:07
-
-
Save ichiroku11/170241ba5de168177221462db6a727a9 to your computer and use it in GitHub Desktop.
Expressionからプロパティ名を取得するサンプル
This file contains hidden or 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.Collections.Generic; | |
using System.Text; | |
using System.Linq; | |
using Xunit; | |
using System.Linq.Expressions; | |
namespace Test { | |
public static class ExpressionHelper { | |
// "@object => new { @object.property1, @object.property2 }"の式からプロパティ名を取得 | |
public static IEnumerable<string> GetMemberNames<TSource>(Expression<Func<TSource, object>> expression) { | |
if (expression.Body is NewExpression @new) { | |
return @new.Members.Select(member => member.Name); | |
} | |
return Enumerable.Empty<string>(); | |
} | |
// "@object => @object.property"の式からプロパティ名を取得 | |
public static string GetMemberName<TSource>(Expression<Func<TSource, object>> expression) { | |
if (expression.Body is MemberExpression member) { | |
return member.Member.Name; | |
} else if (expression.Body is UnaryExpression unary) { | |
// プロパティが値型の場合はBOX化されるため? | |
if (unary.NodeType == ExpressionType.Convert && | |
unary.Operand is MemberExpression operand) { | |
return operand.Member.Name; | |
} | |
} | |
// nullで良いか悩む | |
return null; | |
} | |
} | |
// テスト用 | |
public class Item { | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
public class ExpressionHelperTest { | |
[Fact] | |
public void GetMemberNames_匿名オブジェクトを生成する式からメンバー名一覧を取得() { | |
var members = ExpressionHelper.GetMemberNames<Item>(item => new { item.Id, item.Name }); | |
Assert.Collection(members, | |
member => Assert.Equal("Id", member), | |
member => Assert.Equal("Name", member)); | |
} | |
[Fact] | |
public void GetMemberName_参照型のプロパティにアクセスする式からプロパティ名を取得() { | |
var member = ExpressionHelper.GetMemberName<Item>(item => item.Name); | |
Assert.Equal("Name", member); | |
} | |
[Fact] | |
public void GetMemberName_値型のプロパティにアクセスする式からプロパティ名を取得() { | |
var member = ExpressionHelper.GetMemberName<Item>(item => item.Id); | |
Assert.Equal("Id", member); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment