jeudi 6 janvier 2022

Obtain an instance of a field by Interface type?

I have an interface:

public interface IThings<T> where T : class
{
    public void Play();
}

that populates a class instance with several fields that may be added on to as the project progresses (so no switch statements).

I am attempting to call the Play interface method of a field based on it's interface type, but I do not have access to any particular field.

public class MyClass
{
    public IThings<Widget> Widgets;
    public IThings<Fidget> Fidgets;
    public IThings<Gizmo> Gizmos;
    public IThings<DooDad> DooDads;

    ...

    public void DoWork<T>() where T : IThings<class>
    {
            T.Play(); //does not compile, of course.
    }
}

I have tried dabbling in reflection –which I am not too proficient in– but I'm not sure how to get the instance. I'd also like to avoid relying on convention of field names to class names. I'm sure that would be easier, but it would be a potential source for bugs.

var fieldName = typeof(MyClass).GetRuntimeFields()
    .Where(t => t.FieldType == typeof(IThings<T>))
    .FirstOrDefault().Name;

The above code does actually get the name of the field I'm looking for. I just need to be able to call the method on that field.





Aucun commentaire:

Enregistrer un commentaire