Cannot convert type SomeClass to 'T'
以下代码会出问题:
public static T Protect<T>(Func<T> func, UserLevel pageRole) where T : ActionResult, new()
{
try
{
return func();
}
catch (Exception err)
{
if (typeof(T) is JsonResult)
{
return (T)new JsonResult() ;}
else if (typeof(T) is ActionResult)
{
return (T)new ContentResult();
}throw err;
}
}
得到 Cannot convert type 'JsonResult' to 'T',应该修正为:
return (T)(object)new JsonResult();
Well, you can always placate the compiler by adding an object
cast in the middle:
geoConfigs = (T)(object)GetGeoConfigurationNumericFromDB(items, maMDBEntities);
which will defer the type-check until runtime. However! There is no compiler way to do this otherwise, as it is never going to be happy with string tests like "MamConfiguration"
. Also, generics work well when the code is ... generic - i.e. does the same thing which each type. The code shown is the opposite of generic. It is non-generic code exposed through a generic API. It is always going to be messy inside. Personally I would try to avoid this usage in the first place.
或者:
You should be able to just use Convert.ChangeType()
instead of your custom code:
public T Get<T>(Stats type) where T : IConvertible
{
return (T) Convert.ChangeType(PlayerStats[type], typeof(T));
}
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
2010-10-11 C#笔记26: 与非托管代码交互操作
2010-10-11 T-SQL笔记2:INSERT、UPDATE和DELETE