Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.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# Can';t使用类型为“的变量”;“类型”;转换对象的步骤_C#_Typeof_Activator_Gettype - Fatal编程技术网

C# Can';t使用类型为“的变量”;“类型”;转换对象的步骤

C# Can';t使用类型为“的变量”;“类型”;转换对象的步骤,c#,typeof,activator,gettype,C#,Typeof,Activator,Gettype,这个问题似乎与以前提出的一些问题相似,但请耐心听我说 基本上,我只想在运行时使用表示变量所需类型的字符串来实例化变量。几乎所有现有的问题都给了我这样的答案: Type type = Type.GetType(stringrepresentingType); var newObject = Activator.CreateInstance(type); Type type = Type.GetType(stringRepresentingType); var newObject = (type)

这个问题似乎与以前提出的一些问题相似,但请耐心听我说

基本上,我只想在运行时使用表示变量所需类型的字符串来实例化变量。几乎所有现有的问题都给了我这样的答案:

Type type = Type.GetType(stringrepresentingType);
var newObject = Activator.CreateInstance(type);
Type type = Type.GetType(stringRepresentingType);
var newObject = (type)Activator.CreateInstance(type);
这是可行的,但目前,
newObject
是类型
object
。我希望能够将激活器创建的对象转换为存储在
type
中的类型,因此它看起来如下所示:

Type type = Type.GetType(stringrepresentingType);
var newObject = Activator.CreateInstance(type);
Type type = Type.GetType(stringRepresentingType);
var newObject = (type)Activator.CreateInstance(type);
由于
类型
是一个变量,因此会引发错误。我也尝试过在激活器之前使用
typeof(type)
(type.GetType(stringRepresentingType)
,但都不起作用

如何在不使用if/else的情况下转换
newObject
变量

编辑:
我将在逻辑比较中使用
newObject
(例如==或| |),因此我不能将其保留为type
object
。我知道我可以在事后使用if/else来检查类型,但我很好奇是否有更优雅的解决方案。我会使用
dynamic
,而不是
var
,但不幸的是Unity3D不支持它。

泛型是你的朋友。@Rob,泛型不支持elp在这里-因为只有在运行时才知道类型。@Fabio很好,我错过了用于创建类型的字符串。@GReusch由于您在编译时不知道类型,所以将其强制转换为对象以外的任何对象都没有用。提供的任何intellisense/类型检查都是无用的,因为它在运行时可能是任何内容。
newObject
是l已准备好所需类型的实例。能否演示如何使用它以及为什么需要强制转换它?