感谢下面这篇博文给我的思路:
http://www.cnblogs.com/daimage/archive/2012/04/10/2440186.html
上面文章的博主给出的代码是可用的,但是调用方法时需要写的代码过于冗长,例如博主给出的示例代码
var name = TypeInfoHelper.GetClassPropertiesName<MyClass,List<string>>(s => myClass.UserName);
代码中的List<string>为MyClass.UserName属性的类型,如果要获取一个类型为int的Flag属性还得相应的改为下面这个样子
var name = TypeInfoHelper.GetClassPropertiesName<MyClass,int>(s => customer.Flag);
我想把其中的传入泛型参数的代码拿掉,变成这样子:
TypeInfoHelper.GetPropertyName(s=>myClass.UserName)
是不是变得非常简洁?下面即是全部代码,再次感谢代码哥,致敬!
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var cust = new Customer(); var addr = new Address(cust); string name1 = TypeInfoHelper.GetPropertyName(p => cust.Flag); Console.WriteLine(name1); string name2 = TypeInfoHelper.GetPropertyName(p => addr.Owner.Remark); Console.WriteLine(name2); string name3 = TypeInfoHelper.GetPropertyName(p => cust.Orders); Console.WriteLine(name3); string name4 = TypeInfoHelper.GetPropertyName(p => cust.Orders.FirstOrDefault().Price); Console.WriteLine(name4); Console.ReadLine(); } } public class TypeInfoHelper { public static string GetPropertyName(Expression<Func<Object, Object>> propery) { var body = propery.Body.ToString(); return body.Substring(body.LastIndexOf(".") + 1); } } public class Customer { public string Name { get; set; } public string Remark { get; set; } public int Flag { get; set; } public List<string> Contacts { get; set; } public List<Order> Orders { get; set; } } public class Order { public decimal Price { get; set; } } public class Address { private Customer customer; public string Country { get; set; } public string State { get; set; } public string Street { get; set; } public Customer Owner { get { return customer; } } public Address(Customer owner) { this.customer = owner; } } }