因此,我使用以下实用程序从类的实例中获取字段/属性的名称...
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);
}
}
这对于序列化和其他时候当我需要字段名称的字符串表示形式时非常有用。
但现在,我希望能够在没有类实例的情况下获取字段名称 - 例如,如果我正在设置一个表并希望将列的 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".
}
}
我希望这是有道理的——我不太擅长这个主题的词汇,所以我知道这个问题有点模糊。
您想要做的事情是 Microsoft 创建 System.Reflection 的原因之一
尝试this http://www.csharp-examples.net/reflection-property-names/:
using System.Reflection; // reflection namespace
public static List<Type> GetClassPropertyNames(Type myClass)
{
PropertyInfo[] propertyInfos;
propertyInfos = myClass.GetProperties(BindingFlags.Public);
List<Type> propertyTypeNames = new List<Type>();
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
propertyTypeNames .Add(propertyInfo.PropertyType);
}
return propertyNames;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)