次のコードは「安全」かどうか疑問に思います。「安全」とは、特定のコンパイラバージョンや文書化されていない機能に依存しないことを意味します。プロパティ/フィールド名の文字列を取得したいのですが、強い型付けを使用して宣言したいです(特定のフィールド/プロパティが存在するかどうかをコンパイラに確認させたい)。私の方法は次のようになります。
string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
if (expression.Body is UnaryExpression)
{
var operand = ((UnaryExpression)expression.Body).Operand.ToString();
return operand.Substring(operand.IndexOf(".") + 1);
}
else if (expression.Body is MemberExpression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
else
{
throw new NotImplementedException();
}
}
そして、これが私がそれをどのように使いたいかです:
class Foo
{
public string A { get; set; }
public Bar B { get; set; }
}
class Bar
{
public int C { get; set; }
public Baz D { get; set; }
}
class Baz
{
public int E { get; set; }
}
GetPropertyName<Foo>(x => x.A)
GetPropertyName<Foo>(x => x.B)
GetPropertyName<Foo>(x => x.B.C)
GetPropertyName<Foo>(foo => foo.B.D.E)
助けてくれてありがとう。