そこで、次のユーティリティを使用して、クラスのインスタンスからフィールド/プロパティの名前を取得します...
public static string FieldName<T>(Expression<Func<T>> Source)
{
return ((MemberExpression)Source.Body).Member.Name;
}
これにより、次のことが可能になります。
public class CoolCat
{
public string KaratePower;
}
public class Program
{
public static Main()
{
public CoolCat Jimmy = new CoolCat();
string JimmysKaratePowerField = FieldName(() => Jimmy.KaratePower);
}
}
これは、シリアル化や、フィールド名の文字列表現が必要な場合に最適です。
しかし今、クラスのインスタンスを持たずにフィールド名を取得できるようにしたい-たとえば、テーブルを設定していて、列のフィールド名をクラスの実際のフィールドに動的にリンクしたい場合(リファクタリングなどでは壊れません)。
基本的に、これを達成する方法の構文がよくわからないように感じますが、次のようになると思います。
public static string ClassFieldName<T>(Func<T> PropertyFunction)
{
// Do something to get the field name? I'm not sure whether 'Func' is the right thing here - but I would imagine that it is something where I could pass in a lambda type expression or something of the sort?
}
public class Program
{
public static Main()
{
string CatsPowerFieldName = ClassFieldName<CoolCat>((x) => x.KaratePower);
// This 'CatsPowerFieldName' would be set to "KaratePower".
}
}
それが理にかなっていることを願っています-私はこの主題に関する語彙があまり得意ではないので、質問が少し曖昧であることを知っています.