C# 从MethodInfo.ReturnType创建空实例
假设我可以成功获取方法的返回类型:C# 从MethodInfo.ReturnType创建空实例,c#,generics,C#,Generics,假设我可以成功获取方法的返回类型: var getResult = typeof(T).GetMethod("GetResult"); var ReturnType = getResult.ReturnType; 然后我如何声明该返回类型的null变量?例如: ReturnType somevar = null; 我之所以希望这样做,是因为我在之后有一个循环(当'somevar'被一个实例填充时)。我随后检查循环范围之外的“somevar”的内容,这就是为什么我不能在循环中声明var的原因。
var getResult = typeof(T).GetMethod("GetResult");
var ReturnType = getResult.ReturnType;
然后我如何声明该返回类型的null变量?例如:
ReturnType somevar = null;
我之所以希望这样做,是因为我在之后有一个循环(当'somevar'被一个实例填充时)。我随后检查循环范围之外的“somevar”的内容,这就是为什么我不能在循环中声明var的原因。
var returnType=getResult.returnType代码>等于Type returnType=getResult.returnType代码>
因此,ReturnType
属于type
类型,它包含从方法GetResult
返回的类型的信息
如果要创建该类型的实例,可以使用Activator
:
object somevar = Activator.CreateInstance(returnType);
// assumig that return type of GetResult contains parameterless ctor
但是,您仍然必须对对象
变量进行操作,因此返回类型是通过反射获得的。您将编译时与运行时混淆了。问题是getResult.ReturnType是System.type类型的值
使用“var”语句编译器推断变量“ReturnType”的类型时,它与
System.Type ReturnType = getResult.ReturnType;
然后不能在somevar的声明行中使用ReturnType,因为编译器没有看到它的运行时值
你可能应该做的就是做
object somevar = null;
相反。可能重复的-To repeat(给定ReturnType
表示名为Foo
的类型):“类型Foo
对于您的程序来说是完全未知的。您没有Foo
类引用。您没有IFoo
接口。您甚至不知道Foo
是什么[…]即使您可以将一个对象强制转换到此未知类,您能做什么?您的代码中不能有方法将其作为参数/返回值接受。“——简而言之:为了强制转换到类型,编译器需要知道它。