运营商作为和通用类 [英] Operator as and generic classes
问题描述
我在写 .NET在即时的编译器CLR的脚本,并希望执行方法让通用可以接受的:
I'm writing .NET On-the-Fly compiler for CLR scripting and want execution method make generic acceptable:
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
}
不过,我认为运营商为
将是非常有用的:如果结果类型不是 T
方法将返回< code,而不是一个异常>空,!是否有可能呢?
But I think operator as
will be very useful: if result type isn't T
method will return null
, instead of an exception! Is it possible to do?
推荐答案
您需要添加
where T : class
你的方法声明,例如
to your method declaration, e.g.
T Execute<T>() where T : class
{
顺便说一句,作为一个建议,即通用的包装并没有真正增加多少价值。呼叫者可以这样写:
By the way, as a suggestion, that generic wrapper doesn't really add much value. The caller can write:
MyClass c = whatever.Execute() as MyClass;
或者,如果他们想扔就失败:
Or if they want to throw on fail:
MyClass c = (MyClass)whatever.Execute();
通用包装的方法是这样的:
The generic wrapper method looks like this:
MyClass c = whatever.Execute<MyClass>();
所有三个版本必须指定完全相同的三个实体,只是以不同的顺序,所以没有任何简单或更方便,但通用版本隐藏了所发生的事情,而生的版本都讲清楚是否会有一个抛出或空
。
(这可能是无关紧要的给你,如果你的例子是从您的实际code简化)。
(This may be irrelevant to you if your example is simplified from your actual code).
这篇关于运营商作为和通用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!