I want to create an open delegate to the method ToString(string, IFormatprovider)
of a struct (Int32
, DateTime
, whatever):
public delegate string MyCoverter(ref DateTime from, string format, IFormatProvider provider);
...
var method = typeof(DateTime).GetMethod("ToString", new[] { typeof(string), typeof(IFormatProvider)}); // Works!
var d= Delegate.CreateDelegate(typeof(MyCoverter), null, method); // Exception!
It keeps throwing the ArgumentException with message "Error binding to target method.".
I've read almost all stackoverflow articles on this subject, I have experimented with and without ref
, I have added and removed the null
when creating the delegate. Nothing seems to help.
Has anyone any clue?
* EDIT *
When I create my own struct with the same method, the code above (with DateTime replaced my MyStruct) works perfectly fine.
public struct MyStruct
{
public string ToString(string format, IFormatProvider provider)
{
return null;
}
}
What makes an Int32
or DateTime
so different?
* EDIT *
As requested I added a complete "working" program. What I forgot to mention: I am working on .NET framework 3.5. Furthermore, as I stated before, this is all working on MyStruct
. Except, when I implement the interface IFormattable
, it also does not work anymore.
using System;
namespace OpenDelegates
{
public delegate string MyCoverter<T>(ref T from, string format, IFormatProvider provider)
where T : struct;
class Program
{
static void Main(string[] args)
{
var method = typeof(MyStruct).GetMethod("ToString", new[] { typeof(string), typeof(IFormatProvider) });
var d = Delegate.CreateDelegate(typeof(MyCoverter<MyStruct>), null, method);
method = typeof(DateTime).GetMethod("ToString", new[] { typeof(string), typeof(IFormatProvider) });
d = Delegate.CreateDelegate(typeof(MyCoverter<DateTime>), null, method);
}
}
public struct MyStruct //: IFormattable
{
public string ToString(string format, IFormatProvider provider)
{
return null;
}
}
}
* EDIT *
It all works perfectly on .NET Framework 4.x, but that is NOT a solution for me.