在泛型方法铸造的价值给T [英] Casting value to T in a generic method

查看:84
本文介绍了在泛型方法铸造的价值给T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个摇摇欲坠的财产地图的界面:

I have an interface for a creaky property-map:

interface IPropertyMap
{
   bool Exists(string key);
   int GetInt(string key);
   string GetString(string key);
   //etc..
}



我想创建一个扩展方法像这样:

I want to create an extension method like so:

public static T GetOrDefault<T>(this IPropertyMap map, string key, T defaultValue)
{
    if (!map.Exists(key))
        return defaultValue;
    else
    {
        if (typeof(T) == typeof(int)) return (T)map.GetInt(key);
        //etc..
    }
}



不过,编译器不会让我转换到T.我尝试添加其中T:结构,但似乎并没有帮助。

But the compiler won't let me cast to T. I tried adding where T : struct but that doesn't seem to help.

我缺少什么?

推荐答案

我相信这是因为编译器不知道它需要执行的操作类型。 IIRC,你可以得到它的工作,如果你介绍拳击:

I believe this is because the compiler doesn't know what type of operation it needs to perform. IIRC, you can get it to work if you introduce boxing:

if (typeof(T) == typeof(int)) return (T)(object)map.GetInt(key);



不过,这不是在性能方面的理想选择。

but that's not ideal in terms of performance.

我认为这只是仿制药的限制,很遗憾。

I think it's just a limitation of generics, unfortunately.

这篇关于在泛型方法铸造的价值给T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆