有没有办法在C#3.5中使用反射来确定对象的类型List<MyObject>?例如这里:
Type type = customerList.GetType();
//what should I do with type here to determine if customerList is List<Customer> ?
Run Code Online (Sandbox Code Playgroud)
谢谢.
为了增加卢卡斯的回应,你可能希望通过确保你确实拥有List<something>以下内容来保持防守:
Type type = customerList.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
itemType = type.GetGenericArguments()[0];
else
// it's not a list at all
Run Code Online (Sandbox Code Playgroud)
编辑:上面的代码说,"它是什么样的列表?".要回答'是这个List<MyObject>?',请is正常使用运算符:
isListOfMyObject = customerList is List<MyObject>
Run Code Online (Sandbox Code Playgroud)
或者,如果您拥有的是Type:
isListOfMyObject = typeof<List<MyObject>>.IsAssignableFrom(type)
Run Code Online (Sandbox Code Playgroud)