简体   繁体   中英

Get property name and type by pass it directly

I asked similar questions here And here

This is a sample Type:

    public class Product {

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

}

And I have a Generic class that needs properties to generate some HTML codes:

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
            }
        }

And I use this types as following:

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

GT.Generate();

So I think this process should be more easy as is but I don't know how implement it, I think to pass properties to the generator more simple, something like the followings Pseudo-code:

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

I don't know is this possible or not, I need just two things 1-PropertyName like: IsAllowed 2- property type like : bool . Maybe don't need to pass MainType I use it to get property types so if I can handle like the above don't need it any more.

What is your suggestion to implement something like this?

Is there any better way to do this?

Update

As ArsenMkrt said I found can use MemberExpression but I can't get Property Type, I see the property type in debugging see the picture:

在此输入图像描述

So how can I get property type?

I found it here .

You can use expression tree , than your code will look like this

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

You will need to create custom collection class derived from List for SelectedProperties and create add method like this

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

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM