我知道的typeof(T),但编译器不。怎么修? [英] I know the typeof(T) but the compiler doesn't. How to fix?

查看:315
本文介绍了我知道的typeof(T),但编译器不。怎么修?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写这样一个方法:

public static T Test<T>()
{
  if (typeof(T)==typeof(string))
     return "1241";

  // do something else
}



但我可以'T似乎要弄清楚如何把它关闭。我想回到取决于该方法与调用T的类型值。我需要返回字符串,廉政局的,自定义类,列表等。

but I can't seem to figure out how to pull it off. I want to return values depending on the type of T that the method was invoked with. I need to return strings, int's, custom classes, List etc.

实际用例是一些自定义序列代码,其中很重要的是在反序列化代码知道的类型。反对它应该产生

The actual usecase is some custom serialization code where it is essential that the deserializing code knows the type of the object it should produce.

澄清:上述
的例子提供了以下错误:
不能转换成字符串类型T

Clarification: the example above gives the following error: Cannot convert string to type T

理想的解决方案将工作对值类型和引用类型,并且不包括重载一个虚拟的参数。

The ideal solution would work on value types and reference types, and would not include a dummy parameter for overload resolution.

我开始怀疑是理想的解决方案,虽然存在。

I'm starting to doubt if that ideal solution exists though.

谢谢,卢卡斯

推荐答案

中间投地对象不是很理想,但这样的事情应该做的伎俩:

The intermediate cast to object isn't ideal, but something like this should do the trick:

public static T Test<T>()
{
    if (typeof(T) == typeof(string))
        return (T)(object)"1241";

    // do something else
}

这篇关于我知道的typeof(T),但编译器不。怎么修?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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