通用铸造不起作用
我使用此代码加载数据并将其转换为我使用通用方法获取的类型:
public List<TResult> LoadFromeStreamFile<TResult>(string Location)
{
List<TResult> result = new List<TResult>();
StreamReader reader = new StreamReader(Location);
while (!reader.EndOfStream)
{
result.Add((TResult)reader.ReadLine());
}
reader.Close();
return result;
}
但此代码中有错误 result.Add((TResult)reader.ReadLine());
如何将 string
转换为 TResult
?
I use this code to load data and convert them to a type that I get it using generic methods:
public List<TResult> LoadFromeStreamFile<TResult>(string Location)
{
List<TResult> result = new List<TResult>();
StreamReader reader = new StreamReader(Location);
while (!reader.EndOfStream)
{
result.Add((TResult)reader.ReadLine());
}
reader.Close();
return result;
}
but I have error in this code result.Add((TResult)reader.ReadLine());
How can I cast string
to TResult
??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非
TResult
是object
或string
,否则该转换可能无法工作。假设您实际上尝试创建类似实体的东西,我建议您传入一个Func
或(最好)您使用 LINQ - 所以您根本不需要此方法:如果您仍然需要该方法,您可以使用:
...但我不确定它是否值得。我想如果你经常这样做......
(顺便说一句,当你确实需要从文件中读取时,你应该使用
using
语句,这样即使抛出异常,您的文件句柄也会关闭。)That cast can't possibly work unless
TResult
is eitherobject
orstring
. Assuming you're actually trying to create something like an entity, I would either suggest you pass in aFunc<string, TResult>
or (preferrably) that you use LINQ - so you don't need this method at all:If you still want the method, you could use:
... but I'm not sure whether it's worth it. I suppose if you're doing this a lot...
(On a side note, when you do need to read from a file, you should use a
using
statement so that your file handle gets closed even if an exception is thrown.)您可以通过在“TResult”中实现显式类型转换运算符来实现此目的。
从对象到 TResult 的显式转换。
MSDN 参考
这实际上“在某种程度上”与构造函数相同在“TResult”中,它能够从给定的对象创建构造函数(带有一些假设)。
You can achieve this by implementing explicit type conversion operator in "TResult".
Explicit casting from object to TResult.
MSDN Reference
This is actually 'in a way' same as having a constructor in "TResult" which is able to create a constructor from a given object (with some assumptions).