我需要操作一个TSource
变量。
//代码:
private static DataTable ToDataTable<TSource>(this IList<TSource> data)
{
foreach (TSource item in data)
{
switch (item.ToString())
{
case "Name":
item = "John"; //Error here
break;
}
}
}
错误:
Cannot implicitly convert type string to TSource.
有什么建议吗?
由于TSource是泛型类型,您无法确保到string
的转换是有效的,因此item = "John";
总是向您显示编译错误。
我认为你有两种可能性:
- 您可以假设集合不是
TSource
类型,并设置为IList<string>
- 可以定义可以从字符串显式指定的基类型
例如:
internal class StringConvertible
{
public static implicit operator string(StringConvertible value)
{
return value.StringValue;
}
public static implicit operator StringConvertible(string value)
{
return new StringConvertible
{
StringValue = value
};
}
public virtual string StringValue { get; set; }
}
// ...
private static DataTable ToDataTable<TSource>(this IList<TSource> data)
{
for (int index = 0; index < data.Count; index++)
{
if (!typeof(TSource).IsAssignableFrom(typeof(StringConvertible)))
{
continue;
}
StringConvertible value = data[index] as StringConvertible;
switch (value)
{
case "Name":
value.StringValue = "John";
break;
}
}
// ...
}
除了HuorWords指出的选项之外,另一个选项可能是将自定义转换函数传递到ToDataTable,如下所示:
private static DataTable ToDataTable<TSource>(this IList<TSource> data, Func<string, TSource> itemFromString)
{
foreach (TSource item in data)
{
switch (item.ToString())
{
case "Name":
item = itemFromString("John");
break;
}
}
}