Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将字符串强制转换为泛型_C#_Generics_Casting - Fatal编程技术网

C# 将字符串强制转换为泛型

C# 将字符串强制转换为泛型,c#,generics,casting,C#,Generics,Casting,我有这个方法: public T GetInput<T>() { T result; if( (typeof)T == Type.GetType("string")) { result = GetStringInput(); // returns a string } // Etc for a bunch of different types } public T GetInput() { T结果; if

我有这个方法:

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

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

      // Etc for a bunch of different types
}
public T GetInput()
{
T结果;
if((typeof)T==Type.GetType(“字符串”))
{
result=GetStringInput();//返回一个字符串
}
//等一堆不同的类型
}

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

如果您确定字符串事件是正确的代码,则不能简单地将编译时类型为T的未确定变量赋值给字符串事件。编译器将不允许这样做。要强制执行此操作,可以执行以下操作:

result = (T)(object)GetStringInput();
result = (T)(object)GetStringInput();
这个双重强制转换将明确地告诉编译器,您负责这一行