mardi 18 septembre 2018

Using generic argument from a Type [duplicate]

This question already has an answer here:

So I'm playing around with Reflection and I want to show/print all properties of a class with their values. I have a class that looks like this :

class A
{
    public string a {get; set;}
    public List<string> nums {get;set;}
    public HashSet<int> hashl {get;set;}
    public DateTime dt {get; set;}
    public decimal v {get;set;}
    public A(string _a, decimal _v)
    {
        this.a = _a;
        this.nums = new List<string>();
        this.dt = DateTime.Today.AddDays(-2);
        this.v = _v;
        this.hashl = new HashSet<int>();
    }
}

And I'm getting the job done like this :

void Main()
{
    var val = new A("E", 34.000345345m);
    val.nums.Add("12312312312");
    val.nums.Add("0000054645");
    val.hashl.Add(34);
    val.hashl.Add(567567);
    Type t = typeof(A);
    PropertyInfo[] properties = t.GetProperties();
    foreach(var p in properties)
    {
        Type propertyType = p.PropertyType;
        if (propertyType.IsPrimitive || propertyType == typeof(decimal) || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(TimeSpan))
        {
            Console.WriteLine(String.Format("} = {1:f}", p.Name, p.GetValue(val)));
        }
        else if (propertyType.GetInterface("IEnumerable", true) != null)
        {
            Type genericArugment = propertyType.GetGenericArguments()[0];
            string values = string.Join(", ", (p.GetValue(val, null) as IEnumerable).Cast<object>().ToArray());
            Console.WriteLine("} of type {1} = {2}", p.Name, propertyType.GetGenericArguments()[0], values);
        }
    }
}

This code works fine but I want to use genericArugment as an argument in the Cast function, but the error is :

'genericArugment' is a variable but it is used like a Type

The error is quite clear, but how can I used it as a type since the variable 'genericArugment' contains a type ?





Aucun commentaire:

Enregistrer un commentaire