Operator as and generic classes

前端 未结 5 990
清歌不尽
清歌不尽 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条回答
  •  萌比男神i
    2021-01-07 17:12

    Is there a chance that Execute() might return a value type? If so, then you need Earwicker's method for class types, and another generic method for value types. Might look like this:

    Nullable ExecuteForValueType where T : struct
    

    The logic inside that method would say

    object rawResult = Execute();
    

    Then, you'd have to get the type of rawResult and see if it can be assigned to T:

    Nullable finalReturnValue = null;
    
    Type theType = rawResult.GetType();
    Type tType = typeof(T);
    
    if(tType.IsAssignableFrom(theType))
    {
        finalReturnValue = tType;     
    }
    
    return finalReturnValue;
    

    Finally, make your original Execute message figure out which T is has (class or struct type), and call the appropriate implementation.

    Note: This is from rough memory. I did this about a year ago and probably don't remember every detail. Still, I hope pointing you in the general direction helps.

提交回复
热议问题