lundi 14 juin 2021

How to get the value of a constant field of a static class using the name of that class? [duplicate]

Elements.cs

namespace Tutorials
{
    public static class Elements
    {
        public const string element1 = "asd";
        public const string element2 = "qwe";
        public const string element3 = "zxc";
    }
}

Program.cs

namespace Tutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string FindThisField = "element1";
            string FromThisStaticClass = "Elements";

            string result = GetFieldFromStaticClass(FromThisStaticClass, FindThisField);
            Console.WriteLine(result);
        }

        public static string GetFieldFromStaticClass(string typeName, string fieldName)
        {
            Type t = Type.GetType(typeName);

            FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);
            string value;
            foreach (FieldInfo fi in fields)
            {
                if (fi.Name == fieldName)
                {
                    value = fi.GetValue(null).ToString();
                    return value;
                }
            }
            return null;
        }
    }
}

I can get the constants without any problems, but I also want to be able to get the Type t from a string.

Type t = Type.GetType(typeName);

Is there any better way to do it?

Edit:

I solved the problem by making the following change:

FromThisStaticClass = "Tutorials.Elements";




Aucun commentaire:

Enregistrer un commentaire