Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 16th, 2012  |  syntax: None  |  size: 2.20 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Expression trees: invoking a method with out or ref arguments
  2. class Program
  3. {
  4.     static void Main( string[] args )
  5.     {
  6.         var fooExpr = Expression.Parameter( typeof( Foo ), "f" );
  7.         var parmExpr = Expression.Parameter( typeof( int ).MakeByRefType(), "i" );
  8.         var method = typeof( Foo ).GetMethod( "Method1" );
  9.         var invokeExpr = Expression.Call( fooExpr, method, parmExpr );
  10.         var delegateType = MakeDelegateType( typeof( void ), new[] { typeof( Foo ), typeof( int ).MakeByRefType() } );
  11.         var lambdaExpr = Expression.Lambda( delegateType, invokeExpr, fooExpr, parmExpr );
  12.         dynamic func = lambdaExpr.Compile();
  13.         int x = 4;
  14.         func( new Foo(), ref x );
  15.         Console.WriteLine( x );
  16.     }
  17.  
  18.     private static Type MakeDelegateType( Type returnType, params Type[] parmTypes )
  19.     {
  20.         return Expression.GetDelegateType( parmTypes.Concat( new[] { returnType } ).ToArray() );
  21.     }
  22. }
  23.  
  24. class Foo
  25. {
  26.     public void Method1( ref int x )
  27.     {
  28.         x = 8;
  29.     }
  30. }
  31.        
  32. class Program
  33. {
  34.     static void Main( string[] args )
  35.     {
  36.         var fooExpr = Expression.Parameter( typeof( Foo ), "f" );
  37.         var parmExpr = Expression.Parameter( typeof( int ).MakeByRefType(), "i" );
  38.         var method = typeof( Foo ).GetMethod( "Method1" );
  39.         var invokeExpr = Expression.Call( fooExpr, method, parmExpr );
  40.         var delegateType = MakeDelegateType( typeof( void ), new[] { typeof( Foo ), typeof( int ).MakeByRefType() } );
  41.         var lambdaExpr = Expression.Lambda( delegateType, invokeExpr, fooExpr, parmExpr );
  42.         dynamic func = lambdaExpr.Compile();
  43.         int x = 4;
  44.         func( new Foo(), out x );
  45.         Console.WriteLine( x );
  46.     }
  47.  
  48.     private static Type MakeDelegateType( Type returnType, params Type[] parmTypes )
  49.     {
  50.         return Expression.GetDelegateType( parmTypes.Concat( new[] { returnType } ).ToArray() );
  51.     }
  52. }
  53.  
  54. class Foo
  55. {
  56.     public void Method1( out int x )
  57.     {
  58.         x = 8;
  59.     }
  60. }
  61.        
  62. typeof(int).MakePointerType
  63.        
  64. typeof( int ).MakeByRefType()
  65.        
  66. var parmExpr = Expression.Parameter( typeof( int ).MakeByRefType(), "i" );
  67. var delegateType = MakeDelegateType( typeof( void ), new[] { typeof( Foo ), typeof( int ).MakeByRefType() } );