jeudi 26 décembre 2019

Generate debug automatically with reflection in c#

I'm trying to do Bad Things with reflection in C# - automatically print debug information using an abstract class and reflection. I think I'm very close to having it work, but something's a hair off. You can see from the main below that int can be converted to a IFormattable, but I can't seem to get to the same place with GetCustomAttribute. What am I missing?

namespace daggonit
{
    abstract class Printer
    {
        public void Debug()
        {
            foreach (var b in GetType().GetMembers().Where(x => x.MemberType == MemberTypes.Field))
            {
                var q = b.GetCustomAttribute(typeof(IFormattable));
                Console.WriteLine(q.ToString());
            }
        }
    }

    class Duck : Printer
    {
        public int wings = 2;
        public int bills = 1;

    }

    class Program
    {
        static void Main(string[] args)
        {
            int q = 3;
            var r = (IFormattable)q;
            Console.WriteLine(r.ToString());
            var b = new Duck();
            b.Debug();
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire