Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is parsing the only way to obtain the Member type?

The reflection code below returns:

System.Collections.Generic.IList`1[TestReflection.Car] Cars

How can I get the Cars root type through reflection? Not IList<Car> - how can I get Car?

using System;
using System.Reflection;
using System.Collections.Generic;

namespace TestReflection
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Type t = typeof(Dealer);
            MemberInfo[] mi = t.GetMember("Cars");

            Console.WriteLine("{0}", mi[0].ToString());
            Console.ReadLine();
        }
    }

    class Dealer
    {
        public IList<Car> Cars { get; set; }
    }

    class Car
    {
        public string CarModel { get; set; }
    }
}
like image 416
Hao Avatar asked Dec 15 '10 10:12

Hao


People also ask

Why do we need parsing?

Fundamentally parsing is necessary because different entities need the data to be in different forms. Parsing allows to transform data in a way that can be understood by a specific software. The obvious example are programs: they are written by humans, but they must be executed by computers.

What are the two types of parsing?

There are two types of Parsing: The Top-down Parsing. The Bottom-up Parsing.

What is a parsing method?

Ans: Parsing (also known as syntax analysis) can be defined as a process of analyzing a text which contains a sequence of tokens, to determine its grammatical structure with respect to a given grammar.

What do you mean by parsing and its types?

Parser is a compiler that is used to break the data into smaller elements coming from lexical analysis phase. A parser takes input in the form of sequence of tokens and produces output in the form of parse tree. Parsing is of two types: top down parsing and bottom up parsing.


1 Answers

The easiest way would be to produce a PropertyInfo that represented the property in question and then its underlying type via PropertyInfo.PropertyType. Then it's just a matter of retrieving the type arguments for this generic type, for which you could use Type.GetGenericArguments.

Type carsElementType = typeof(Dealer)
                        .GetProperty("Cars") 
                        .PropertyType // typeof(IList<Car>)
                        .GetGenericArguments() // new[] { typeof(Car) }
                        .Single(); // typeof(Car)
like image 196
Ani Avatar answered Sep 24 '22 20:09

Ani