Generic type to comma delimited
I'm trying to convert a generic value into an array of generic values so that I can comma delimit them. However, I can't convert from my generic type into an array of generic types. hopefully some code will help make things clearer...
public T Item
{
get { return item; }
set { item = value; }
}
public string GetItemAsString()
{
string itemString = Item.ToString();
if(Item.GetType().IsArray)
{
itemString = string.Join(",", Item);
}
return itemStri开发者_如何学Pythonng;
}
Can someone point me in the right direction?
Thanks.
Maybe something like this?
public class Tester<T, R> where T : IEnumerable<R>
{
private T _item;
public T Item
{
get { return _item; }
set { _item = value; }
}
public string GetItemAsString()
{
IEnumerable<R> items = _item as IEnumerable<R>;
if (items != null)
{
StringBuilder str = new StringBuilder();
int count = 0;
foreach (R item in items)
{
str.Append(count++ > 0 ? "," : String.Empty);
str.Append(item.ToString());
}
return str.ToString();
}
return null;
}
}
Im not exactly sure if this is what your trying to do but you could try something like this.
public T Item
{
get { return item; }
set { item = value; }
}
public string GetItemAsString()
{
string itemString = Item.ToString();
if(Item.GetType().IsArray)
{
itemString = String.Join(",", (Item as IEnumerable<object>).Select(item => item.ToString()).ToArray());
}
return itemString;
}
精彩评论