lundi 26 juillet 2021

How to get static readonly property using reflection in some class

With the code block below, I am getting static variables of a class and the value of that variable.

static void Main(string[] args)
{
    var ax = GetClassPropertyValues("SomeClass");
}

public static List<string> GetClassPropertyValues(string className)
{
    var fieldInfos = Type.GetType($"ConsoleApp1.{className}, ConsoleApp1")
        .GetFields(
            BindingFlags.Instance
            | BindingFlags.Public
            | BindingFlags.FlattenHierarchy
            | BindingFlags.Static
        );

    var propertyValues = new List<string>();

    foreach (var fieldInfo in fieldInfos)
    {
        propertyValues.Add(fieldInfo.GetValue(null).ToString());
    }

    return propertyValues;
}

Classes

public abstract class SomeAbstractClass
{
    public static string List = "List";
}

public class SomeClass: SomeAbstractClass
{
    public static string Price = "Price";
}       

When I just set static variables to read-only then I don't get those variables. How can I get these variables ?





Aucun commentaire:

Enregistrer un commentaire