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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值