Dynamically creating private/internal types and delegates (UserCallBack and AsyncStreamReader)
When trying to create a callback into Console.Out, I tried to create a instance of the internal class AsyncStreamReader (which has a dependency on the private delegate UserCallBack). This workded ok (see code below), but it didn’t have the expected behaviour (I did get a call into the outputReadNotifyUser Lambda method, but it only happened once and there was no value in its text variable) .
I actually found a better way (see next blog post), but meanwhile here is an example of how to use reflection to create instance of private types and delegates.
//Not currently working, but shows how to create a private Delegate and Type
var currentProcess = Processes.getCurrentProcess();
Action<string> outputReadNotifyUser =
(text)=>{
"outputReadNotifyUser: {0}".info(text);
};
var userCallBackType = PublicDI.reflection.getType("UserCallBack");
var userCallBack = Delegate.CreateDelegate(userCallBackType, outputReadNotifyUser, typeof(Action<string>).method("Invoke"));
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream);
System.Console.SetOut(streamWriter);
streamWriter.AutoFlush = true;
var oParams = new object[] { currentProcess,memoryStream, userCallBack , Encoding.UTF8};
var asyncStreamReader = PublicDI.reflection.getType("AsyncStreamReader");
var aSyncReader = asyncStreamReader.ctors()[0].Invoke(oParams);
aSyncReader.invoke("BeginReadLine");
Console.Out.WriteLine("aaaa".line());
Console.Out.WriteLine("aaaa".line());
return "ok";
//using System.Text
//using System.IO
//using System.Diagnostics

