相关疑难解决方法(0)

运算符as和泛型类

我正在为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,而不是异常!有可能吗?

.net c# generics operators on-the-fly

29
推荐指数
3
解决办法
1万
查看次数

标签 统计

.net ×1

c# ×1

generics ×1

on-the-fly ×1

operators ×1