Operator as and generic classes

前端 未结 5 1011
清歌不尽
清歌不尽 2021-01-07 16:39

I\'m writing .NET On-the-Fly compiler for CLR scripting and want execution method make generic acceptable:

object Execute()
{
  return type.InvokeMember(..);         


        
5条回答
  •  一个人的身影
    2021-01-07 16:58

    You need to add

    where T : class
    

    to your method declaration, e.g.

    T Execute()  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();
    

    All three versions have to specify exactly the same three entities, just in different orders, so none are any simpler or any more convenient, and yet the generic version hides what is happening, whereas the "raw" versions each make it clear whether there will be a throw or a null.

    (This may be irrelevant to you if your example is simplified from your actual code).

提交回复
热议问题