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();
}
开发者_开发技巧
You can achieve that, with lots of reflection (both to find the correct T
, and then to invoke via MakeGenericMethod
etc); however: you aren't using the generic features, so remove them! (or have a secondary non-generic API):
public static string ConvertToString(this IEnumerable list)
{
StringBuilder sb = new StringBuilder();
foreach (object item in list)
{
sb.Append(item.ToString());
}
return sb.ToString();
}
and
IList list = o as IList;
if (list != null)
{
string value = list.ConvertToString();
}
(you can also use IEnumerable
in the above step, but you need to be careful with string
etc if you do that)
Instead of coding the extension method against IList<T>, you could code it against IEnumerable, then it'd be:
public static string ConvertToString(this IEnumerable list)
{
StringBuilder sb = new StringBuilder();
foreach (object item in list)
{
sb.Append(item.ToString());
}
return sb.ToString();
}
Then you could check if o
is an IEnumerable:
object o = new List<int>() { 1, 2, 3, 4, 5 };
if (o is IEnumerable)
{
string value = ((IEnumerable) o).ConvertToString();
}
Use System.Type to see if your type is an arrat (IsArray) and if it's a generic type (IsGenericType)
精彩评论