none
How to convert a string to a C# class hierarchy command RRS feed

  • Question

  • I get passed a argument which represents the nested class hierarchy, how can I do the conversion from a string to command?The output looks:

    Opqr = Abcd.Ef.Ghij.Klmn.Opqr
    Opqr = 123456789

    Pro grammatically how can I make both print out the same value? The comments in the program also poses the issue I have

    using System;
    class Str2Cmd
    {
        public static void Main()
        {
            // This is the argument get passed
            string arguments = "/Abcd/Ef/Ghij/Klmn/Opqr";
            // The above argument has to morph and I should be able to do as the second Console.WriteLine()
            arguments = arguments.Replace("/", ".").Trim('.');
            Console.WriteLine("Opqr = {0}", arguments);
            // How can I convert the string arguments to the C# class hierarchy
            Console.WriteLine("Opqr = {0}", Abcd.Ef.Ghij.Klmn.Opqr);
            Console.ReadLine();
        }
    
        public class Abcd
        {
            public class Ef
            {
                public class Ghij
                {
                    public class Klmn
                    {
                        public static uint Opqr = 123456789;
                    }
                }
            }
        }
    }


    Thursday, January 18, 2018 5:47 AM

Answers

  • Check this:

    string arguments = "/Abcd/Ef/Ghij/Klmn/Opqr";
    string[] names = arguments.Trim().Trim( '/' ).Split( '/' );
    Type t = typeof( Str2Cmd );
    foreach( var n in names.Take( names.Length - 1 ) )
    {
       t = t.GetNestedType( n );
    }
    var f = t.GetField( names.Last() );
    object val = f.GetValue( null );
    Console.WriteLine( arguments );
    Console.WriteLine( val );


    • Edited by Viorel_MVP Thursday, January 18, 2018 6:07 AM
    • Marked as answer by ananda vardhana Thursday, January 18, 2018 6:20 AM
    Thursday, January 18, 2018 6:06 AM

All replies

  • Check this:

    string arguments = "/Abcd/Ef/Ghij/Klmn/Opqr";
    string[] names = arguments.Trim().Trim( '/' ).Split( '/' );
    Type t = typeof( Str2Cmd );
    foreach( var n in names.Take( names.Length - 1 ) )
    {
       t = t.GetNestedType( n );
    }
    var f = t.GetField( names.Last() );
    object val = f.GetValue( null );
    Console.WriteLine( arguments );
    Console.WriteLine( val );


    • Edited by Viorel_MVP Thursday, January 18, 2018 6:07 AM
    • Marked as answer by ananda vardhana Thursday, January 18, 2018 6:20 AM
    Thursday, January 18, 2018 6:06 AM
  • Wow!! This is amazing. I am new to C# I am from the C world and every time I think there is no way out, there is a way! Thanks a lot Vicrel!! 
    Thursday, January 18, 2018 6:22 AM