Access interface methods without referring the class

后端 未结 5 1078
礼貌的吻别
礼貌的吻别 2021-01-22 20:26

Say I have an Interface like this in a project called \"Interface\":

public interface TestInterface
{
    string Operation();
}

and class which

5条回答
  •  情话喂你
    2021-01-22 21:03

    Is there any way to access the methods via Interface only

    Yes, there is. You can dynamically load an assembly with TestClass without referencing it, create its instance via Activator.CreateInstance and cast it to interface type:

    var assembly = Assembly.Load(...);
    var typeFromAssembly = assembly.GetTypes()...;
    var myInterfaceVar = (TestInterface)Activator.CreateInstance(typeFromAssembly);
    

    ...or... you may use one of existing DI-frameworks (e.g. MEF) and do the same thing more right way:

    [Import]
    private TestInterface myInterfaceField;
    

    or:

    var myInterfaceVar = compositionContainer.GetExportedValue();
    

    Depending of the way you prefer, you may ask more concrete question.

提交回复
热议问题