Operator as and generic classes

前端 未结 5 984
清歌不尽
清歌不尽 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 17:09

    It seems like you are just adding a wrapper method for casting to the type the user wants, thus only adding overhead to the execution. For the user, writing

    int result = Execute();
    

    isn't much different from

    int result = (int)Execute();
    

    You can use the out modifier to write the result into a variable in the caller's scope, and return a boolean flag to tell whether it succeeded:

    bool Execute(out T result) where T : class
    {
        result = Execute() as T;
        return result != null;
    }
    

提交回复
热议问题