我正在为CLR脚本编写.NET On-the-Fly编译器,并希望执行方法使得泛型可接受:
object Execute()
{
return type.InvokeMember(..);
}
T Execute<T>()
{
return Execute() as T; /* doesn't work:
The type parameter 'T' cannot be used with the 'as' operator because
it does not have a class type constraint nor a 'class' constraint */
// also neither typeof(T) not T.GetType(), so on are possible
return (T) Execute(); // ok
}
Run Code Online (Sandbox Code Playgroud)
但我认为运算符as将非常有用:如果结果类型不是T方法将返回null,而不是异常!有可能吗?