lundi 4 mai 2020

Is there a way to use interfaces to achieve a similar result?

I have an application which dynamically references types within my application at launch using reflection.

Each of my types have a constant defined in them as such:

public class Class : IClassInterface
{
    public const string ClassConstant = "Class Constant Value";
}

During my application's initialization, I access that constant through reflection as such:

foreach (Type type in Assembly.GetExecutingAssembly().DefinedTypes)
    if (typeof(IClassInterface).IsAssignableFrom(type))
    {
        string constantString = type.GetField("ClassConstant")?.GetRawConstantValue()?.ToString();
    }

In a completely different place in my application, I need to retrieve that constant again, which would require me to use reflection again. It seems to be a little messy and I'm wondering if someone has an idea on how I could do this perhaps a bit differently.

I originally tried using a public property instead of a constant, but I found that the property is only available once the class is instanciated, so it required me to call Activator.CreateInstance on each type just to read the value of a string that won't change during the application's lifetime.

The property was readable during runtime thanks to the interface, but required class instanciation. The constant does not require class instanciation, but is not readable during runtime because it cannot be defined as a member of the interface. So I'm stuck in a sort of chicken and egg situation.





Aucun commentaire:

Enregistrer un commentaire