【发布时间】:2016-06-21 19:32:14
【问题描述】:
我有一个有几个List<T> 属性的类。我需要能够动态确定给定列表的大小。
下面是我到目前为止的代码。我怎样才能摆脱 switch 语句并将其作为一个一般性语句?我很想投给List<T>,但这不起作用。
switch (Inf.GetType()
.GetProperty(propertyName)
.GetValue(Inf)
.GetType()
.UnderlyingSystemType.GenericTypeArguments[0]
.Name)
{
case "String":
dynamicListCount = ((List<string>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count;
break;
case "Int32":
dynamicListCount = ((List<Int32>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count;
break;
default:
throw new Exception("Unknown list type");
}
【问题讨论】:
-
你为什么不投成
IList? -
不知道你为什么不使用
List<T>.Count
标签: c# list generics reflection