Tôi muốn tách riêng các biến số IEnumerable
theo loại của chúng. Mã của tôi là như thế này:làm thế nào để chỉ nhận được loại Enumerable?
if (type is IEnumerable)
{
var listGenericType = type.GetType().GetGenericTypeDefinition().Name;
listGenericType = listGenericType.Substring(0, listGenericType.IndexOf('`'));
if (listGenericType == "List") {
//do something
}
else if (listGenericType == "HashSet") {
//do something
}
}
Khi tôi sử dụng type.GetType().GetGenericTypeDefinition().Name
, các listGenericType
là như List`1
hoặc HashSet`1
nhưng tôi muốn nó như List
hoặc HashSet
. Do đó, tôi đã sử dụng Substring
để xử lý vấn đề này!
Có cách nào để xử lý vấn đề này mà không cần xử lý sau string
không? Tôi có ý nghĩa giống như mã bên dưới:
if (type is IEnumerable)
{
var listGenericType = type.GetType().GetGenericTypeDefinitionWithoutAnyNeedForPostProcessing();
if (listGenericType == "List") {
//do something
}
else if (listGenericType == "HashSet") {
//do something
}
}
https://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx –