所以我在玩Reflection
,我想显示/打印类的所有属性及其值。我有一个看起来像这样的课程:
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>();
}
}
我正在像这样完成工作:
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("{{{0}}} = {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("{{{0}}} of type {1} = {2}", p.Name, propertyType.GetGenericArguments()[0], values);
}
}
}
这段代码可以正常工作,但是我想在Cast函数中使用genericArugment
作为参数,但是错误是:
'genericArugment'是一个变量,但其用法类似于Type
错误非常明显,但是由于变量'genericArugment'包含类型,我该如何将其用作类型?