将字符串转换为通用 [英] Casting a string to a generic

查看:120
本文介绍了将字符串转换为通用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法:

public T GetInput<T>()
{
     T result;

     if( (typeof)T == Type.GetType("string"))
     {
           result = GetStringInput(); // returns a string
     }

      // Etc for a bunch of different types
}

我得到的错误是我不能隐式地将字符串转换为T。函数的要点是能够获得任何指定类型的输入,并确保在返回之前对输入执行类型验证。想法?

The error I'm getting is that I can't implicitly cast a string to a "T". The point of the function is to be able to get input of any specified type and make sure to do type validation on the input before returning it. Ideas?

推荐答案

不能简单地将未确定的变量分配给编译时类型 T 你肯定它是正确的代码。编译器不会允许它。强制这样做你可以这样做:

You cannot simply assign variable of undetermined on compile time type T with string event if you are certain that it is correct code. Compiler will not allow it. To force this you can do this:

result = (T)(object)GetStringInput();

这个双重强制转换会明确地告诉编译器你对这一行负责。

this dual cast will explicitly say to compiler that you take responsibility for this line.

这篇关于将字符串转换为通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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