日期:2014-05-18 浏览次数:20962 次
class Item { public GUID Id { get; set; } public string Name { get; set; } }
Item item = new Item();
string name = typeof(Item).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)[1].Name;
------解决方案--------------------
将item封装成类,里面发布Name属性
------解决方案--------------------
public string GetPropertyName(Expression<Func<Item, string>> expr) { var name = ((MemberExpression)expr.Body).Member.Name; return name; } string name = GetPropertyName(o=>o.Name);
------解决方案--------------------
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string name = GetPropertyName(o => o.Name); Console.WriteLine(name); string id = GetPropertyName(o => o.Id); Console.WriteLine(id); Console.ReadKey(); } public static string GetPropertyName<T>(Expression<Func<Item, T>> expr) { var name = ((MemberExpression)expr.Body).Member.Name; return name; } } class Item { public int Id { get; set; } public string Name { get; set; } } }