Wil*_*iam 8 c# reflection lambda func
所以我使用以下实用程序从类的实例中获取字段/属性的名称...
public static string FieldName<T>(Expression<Func<T>> Source)
{
return ((MemberExpression)Source.Body).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
这允许我执行以下操作:
public class CoolCat
{
public string KaratePower;
}
public class Program
{
public static Main()
{
public CoolCat Jimmy = new CoolCat();
string JimmysKaratePowerField = FieldName(() => Jimmy.KaratePower);
}
}
Run Code Online (Sandbox Code Playgroud)
当我需要字段名称的字符串表示时,这非常适合序列化和其他时间.
但是现在,我希望能够获得字段名称而没有类的实例 - 例如,如果我正在设置一个表并希望将列的FieldNames动态链接到类中的实际字段(因此重构)等等不会破坏它).
基本上,我觉得我还没有完全掌握如何实现这一点的语法,但我想它会看起来像这样:
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".
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这是有道理的 - 我对这个主题的词汇不是很了解所以我知道这个问题有点模糊.
我用两种方法来做到这一点。
第一个是可以在任何对象上使用的扩展方法。
public static string GetPropertyName<TEntity, TProperty>(this TEntity entity, Expression<Func<TEntity, TProperty>> propertyExpression)
{
return propertyExpression.PropertyName();
}
Run Code Online (Sandbox Code Playgroud)
其用法如下
public CoolCat Jimmy = new CoolCat();
string JimmysKaratePowerField = Jimmy.GetPropertyName(j => j.KaratePower);
Run Code Online (Sandbox Code Playgroud)
当我没有对象时我使用第二个。
public static string PropertyName<T>(this Expression<Func<T, object>> propertyExpression)
{
MemberExpression mbody = propertyExpression.Body as MemberExpression;
if (mbody == null)
{
//This will handle Nullable<T> properties.
UnaryExpression ubody = propertyExpression.Body as UnaryExpression;
if (ubody != null)
{
mbody = ubody.Operand as MemberExpression;
}
if (mbody == null)
{
throw new ArgumentException("Expression is not a MemberExpression", "propertyExpression");
}
}
return mbody.Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
这可以像这样使用
string KaratePowerField = Extensions.PropertyName<CoolCat>(j => j.KaratePower);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2282 次 |
| 最近记录: |