Cannot convert type SomeClass to 'T'

简介: 以下代码会出问题: public static T Protect(Func func, UserLevel pageRole) where T : ActionResult, new(){    try    {        return func();    }    catch (Exce...

以下代码会出问题:

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));
}
Creative Commons License本文基于 Creative Commons Attribution 2.5 China Mainland License发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名 http://www.cnblogs.com/luminji(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。
目录
相关文章
|
存储 SQL 关系型数据库
【MySQL异常】Row size too large (> 1982). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNA
【MySQL异常】Row size too large (> 1982). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNA
127 0
|
Java
【ES异常】mapper [sortNum] of different type, current_type [long], merged_type [keyword]
【ES异常】mapper [sortNum] of different type, current_type [long], merged_type [keyword]
138 0
|
Scala
TYPE
TYPE
140 0
YOLO V5出现RuntimeError: result type Float can‘t be cast to the desired output type long int解决方法
YOLO V5出现RuntimeError: result type Float can‘t be cast to the desired output type long int解决方法
680 0
|
存储 JSON Linux
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (ch
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (ch
|
XML Java 数据库连接
Open quote is expected for attribute "{1}" associated with an element type "id".
Open quote is expected for attribute "{1}" associated with an element type "id".
199 0
Open quote is expected for attribute "{1}" associated with an element type "id".