我需要操纵一个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;
}
}
// ...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句