samedi 25 février 2017

C# - RuntimeTypeHandle.Allocate()

I'm attempting to write a slightly tweaked Array.Sort() method implementation based in large part off of the standard CLR implementation. The source online contains the following method to instantiate the ArraySortHelper object.

private static ICustomArraySortHelper<TKey, TValue> CreateArraySortHelper()
{
    if (typeof(IComparable<TKey>).IsAssignableFrom(typeof(TKey)))
    {
        defaultArraySortHelper = (ICustomArraySortHelper<TKey, TValue>)RuntimeTypeHandle.Allocate(typeof(GenericCustomArraySortHelper<string, string>).TypeHandle.Instantiate(new Type[] { typeof(TKey), typeof(TValue) }));
    }
    else
    {
        defaultArraySortHelper = new CustomArraySortHelper<TKey, TValue>();
    }
    return defaultArraySortHelper;
}

When I try to compile, however, both the RuntimeTypeHandle.Allocate() and TypeHandle.Instantiate() calls come back as not being defined.

'System.RuntimeTypeHandle' does not contain a definition for 'Allocate' 'System.RuntimeTypeHandle' does not contain a definition for 'Instantiate' and no extension method 'Instantiate' accepting a first argument of type 'System.RuntimeTypeHandle' could be found (are you missing a using directive or an assembly reference?)

The MSDN documentation also appears to be lacking these methods. Why can't I access these? Am I missing some reference? Lastly, if I did not want to add an external reference, what is the best line of code to replace the offending line while maintaining the same objective? It's not clear to me why reflection is required for this construction. Can I get by with a new call similar to the else branch of the code?





Aucun commentaire:

Enregistrer un commentaire