mardi 5 décembre 2017

Get Readable name of Nested Type

I have a type with a nested Event type Created. I want to get the readable type names of the event type without writing custom code like in the GetNestedName<T> method below. I just want to get the string 'SomeAggregate.Created' exactly like how you must reference the type in code - typeof( SomeAggregate.Created ). Using the properties on type seems to only return either 'Created' or the full name.

I would expect Name on Type to return what I want, but it doesn't. Am I missing something? Surely there is something built-in to the framework to do this?

Code:

static void Main( string[] args )
    {       
        Console.WriteLine( nameof( SomeAggregate.Created ) ); //Created
        Console.WriteLine( typeof( SomeAggregate.Created ).Name ); //Created
        Console.WriteLine( typeof( SomeAggregate.Created ).FullName ); //MyAssembly.SomeAggregate.Created

        Console.WriteLine( GetNestedName<SomeAggregate.Created>() );        
        //prints: SomeAggregate.Created, but why do I need custom code to get this??

        Console.ReadKey();
    }

    static string GetNestedName<T>()
    {
        var type = typeof( T );
        if ( !type.IsNested )
            return type.Name;

        return $"{type.DeclaringType.Name}.{type.Name}";
    }
}

public class SomeAggregate
{
    public class Created : Event
    {
    }
}

public abstract class EVent
{
}





Aucun commentaire:

Enregistrer un commentaire