如何检测对象是否为泛型 List 类型并强制转换为所需类型?
我有一个用于将通用列表转换为字符串的扩展方法。
public static string ConvertToString<T>(this IList<T> list)
{
StringBuilder sb = new StringBuilder();
foreach (T item in list)
{
sb.Append(item.ToString());
}
return sb.ToString();
}
我有一个对象类型为包含列表的对象;该列表可以是 List
、List
、List
任何类型的列表。
有没有一种方法可以检测到该对象是通用列表,从而转换为该特定通用列表类型以调用 ConvertToString
方法?
//ignore whats happening here
//just need to know its an object which is actually a list
object o = new List<int>() { 1, 2, 3, 4, 5 };
if (o is of type list)
{
string value = (cast o to generic type).ConvertToString();
}
I have an extension method for converting a generic list to string.
public static string ConvertToString<T>(this IList<T> list)
{
StringBuilder sb = new StringBuilder();
foreach (T item in list)
{
sb.Append(item.ToString());
}
return sb.ToString();
}
I have an object which is of type object that holds a list; the list could be List<string>
, List<int>
, List<ComplexType>
any type of list.
Is there a way that I can detect that this object is a generic list and therefore cast to that specific generic list type to call the ConvertToString
method?
//ignore whats happening here
//just need to know its an object which is actually a list
object o = new List<int>() { 1, 2, 3, 4, 5 };
if (o is of type list)
{
string value = (cast o to generic type).ConvertToString();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过大量反射来实现这一点(既找到正确的
T
,然后通过MakeGenericMethod
等进行调用);但是:您没有使用通用功能,因此请删除它们! (或者有一个辅助非通用 API):并且
(您也可以在上述步骤中使用
IEnumerable
,但如果这样做,您需要小心string
等)You can achieve that, with lots of reflection (both to find the correct
T
, and then to invoke viaMakeGenericMethod
etc); however: you aren't using the generic features, so remove them! (or have a secondary non-generic API):and
(you can also use
IEnumerable
in the above step, but you need to be careful withstring
etc if you do that)您可以根据 IEnumerable 对其进行编码,而不是针对 IList编码扩展方法,然后它会是:
然后您可以检查
o
是否是 IEnumerable:Instead of coding the extension method against IList<T>, you could code it against IEnumerable, then it'd be:
Then you could check if
o
is an IEnumerable:使用 System.Type 查看您的类型是否为 Arrat (IsArray) 以及是否为泛型类型 (IsGenericType)
Use System.Type to see if your type is an arrat (IsArray) and if it's a generic type (IsGenericType)