Skip to main content
 首页 » 编程设计

c#之通过直接传递获取属性名称和类型

2024年02月23日16sharpest

我问过类似的问题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,如:IsAllowed 2- 属性类型,如:bool。也许不需要传递 MainType 我用它来获取属性类型,所以如果我能像上面那样处理就不再需要它了。

你对实现这样的东西有什么建议?

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

更新

正如 ArsenMkrt 所说,我发现可以使用 MemberExpression 但我无法获取属性类型,我在调试中看到了属性类型,请参见图片:

那么如何获取属性类型呢?

我找到了 here .

请您参考如下方法:

您可以使用 expression tree ,那么您的代码将如下所示

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

您需要为 SelectedProperties 创建从 List 派生的自定义集合类,并像这样创建添加方法

   //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); 
   } 

希望对你有帮助