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

标签 c# c#-4.0 properties

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

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

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

更新

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

enter image description here

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

我找到了 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);
   }

希望对你有帮助

关于c# - 通过直接传递获取属性名称和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222783/

相关文章:

apache-kafka - 卡夫卡 : Connection to node failed authentication due to: Authentication failed due to invalid credentials with SASL mechanism SCRAM-SHA-256

c++ - 另一个宏中的 Q_PROPERTY 宏

c# - .NET 4.0 中的 SpellCheck.IsEnabled ="True"(不适用于德语 .NET 4.0 框架)

c# - 如何在不损失图像质量的情况下将图像转换为base64格式?

.net - 在WPF中使用OpenFileDialog时没有文件的文件夹路径?

.net - .NET 如何解析类型?

windows - 如何将位图图像保存到本地文件夹 Windows 应用商店应用程序

c# - 为什么这个方法,我认为是更快的,更慢的?

c# - 在Azure服务器中每天自动调用一次API

java - 如何从后台定期任务修改模型属性?