1
我问类似的问题here而here获取属性名称和类型传递直接
这是一个样本类型:
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
,但我不能让物业类型,我看到在调试物业类型看图片:
那么如何我可以获得房产类型吗?我发现它here。
感谢您的回答,这真的很有帮助,但我无法获得'PropertyType',我在调试中看到属性类型,但我不知道g等等,因为我更新问题,你知道如何得到它吗? – Saeid 2012-04-19 07:34:08
@Saeid,我相信((PropertyInfo)body.Member).PropertyType将返回你正在寻找的类型 – 2012-04-19 09:03:15