2012-04-19 89 views
1

我问类似的问题herehere获取属性名称和类型传递直接

这是一个样本类型:

public class Product { 

    public string Name { get; set; } 
    public string Title { get; set; } 
    public string Category { get; set; } 
    public bool IsAllowed { get; set; } 

} 

而且我有需要的属性生成一些HTML代码的通用类:

public class Generator<T> { 

    public T MainType { get; set; } 
    public List<string> SelectedProperties { get; set; } 

    public string Generate() { 

     Dictionary<string, PropertyInfo> props; 
     props = typeof(T) 
       .GetProperties() 
       .ToDictionary<PropertyInfo, string>(prop => prop.Name); 

     Type propType = null; 
     string propName = ""; 
     foreach(string item in SelectedProperties) { 
      if(props.Keys.Contains(item)) { 
       propType = props[item].PropertyType; 
       propName = item; 

       // Generate Html by propName & propType 
      } 
     } 

而且我用这个类型如下:

Product pr = new Product(); 
Generator<Product> GT = new Generator<Product>(); 
GT.MainType = pr; 
GT.SelectedProperties = new List<string> { "Title", "IsAllowed" }; 

GT.Generate(); 

所以我认为这个过程应该更容易,不过我不知道如何实现它,我想通过性能发电机更简单,有点像以下伪代码:

GT.SelectedProperties.Add(pr.Title); 
GT.SelectedProperties.Add(pr.IsAllowed); 

我不知道这是否可能,我只需要两件事1-PropertyName like:IsAllowed 2-属性类型如:bool。也许不需要通过MainType我使用它来获取属性类型,所以如果我可以像上面那样处理,就不需要它了。

你有什么建议来实现这样的事情?

有没有更好的方法来做到这一点?

更新

正如ArsenMkrt说我发现可以用MemberExpression,但我不能让物业类型,我看到在调试物业类型看图片:

enter image description here

那么如何我可以获得房产类型吗?我发现它here

回答

4

您可以使用expression tree,比你的代码看起来像这样

GT.SelectedProperties.Add(p=>p.Title); 
GT.SelectedProperties.Add(p=>p.IsAllowed); 

您需要创建一个从列表导出SelectedProperties自定义集合类,并创建添加方法类似这样的

//where T is the type of your class 
    public string Add<TProp>(Expression<Func<T, TProp>> expression) 
    { 
     var body = expression.Body as MemberExpression; 
     if (body == null) 
      throw new ArgumentException("'expression' should be a member expression"); 
     //Call List Add method with property name 
     Add(body.Member.Name); 
    } 

希望这有助于帮助

+0

感谢您的回答,这真的很有帮助,但我无法获得'PropertyType',我在调试中看到属性类型,但我不知道g等等,因为我更新问题,你知道如何得到它吗? – Saeid 2012-04-19 07:34:08

+0

@Saeid,我相信((PropertyInfo)body.Member).PropertyType将返回你正在寻找的类型 – 2012-04-19 09:03:15