【发布时间】:2021-12-09 16:49:45
【问题描述】:
使用 C# 10 我正在尝试将 IEnumerable<String>? 转换为 IEnumerable<T>:
IEnumerable<String>? inputs = getValues();
if (inputs is null)
return false;
Type type = typeof(List<>).MakeGenericType(typeof(T));
IList? outputs = (IList?)Activator.CreateInstance(type);
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter is null || outputs is null || !converter.CanConvertFrom(typeof(String)))
return false;
foreach (String input in inputs) {
if (converter.IsValid(input))
outputs.Add(converter.ConvertFromString(input));
}
var texpression = new TExpression<T>(outputs);
即使我使用outputs.ToList(),最后一行也会出现错误:
Cannot convert from 'System.Collections.IList' to 'System.Collections.Generic.IEnumerable<T>'
TExpression 构造函数是:
public TExpression(IEnumerable<T> values) {
Values = values;
}
我尝试更改转换代码的类型,但总是在某处出现错误。
如何解决这个问题,以便在不更改构造函数的情况下使用构造函数?
更新
使用以下内容:
IList<T> outputs = (IList<T>)Activator.CreateInstance(type);
...
foreach (string input in inputs) {
if (converter.IsValid(input))
outputs.Add((T)converter.ConvertFromString(input));
}
我收到警告(我正在使用<Nullable>enable</Nullable>):
Converting null literal or possible null value to non-nullable type.
T 可以是可空类型 (Int32?) 或不可空类型 (Int32)。
我可以将代码行更改为:
T? output = (T?)converter.ConvertFromString(input);
这修复了警告,但它正确吗?
如果 T 是不可为空的类型怎么办?
【问题讨论】:
-
输出是一个 IList 并且 TExpression 返回一个 IEnumerable。
-
IList 是什么?使用泛型类型转换..
outputs = (IList<T>)…