mercredi 12 février 2020

C# Proxy different class conditionally at run time

I need to have a class that choose which otherclass use and then "emulate" it. Have a look at this sample pseudo-code and consider:

  • I must use Framerork 2.0 on a win32 system
  • Proxy, A and B implement the same interface,

my problem is to "cast" _privateGenericProxyClass to type A or type B. If i use _privateGenericProxyClass as object and then try to cast to A o B i get null reference or generic error.

namespace my.namespace
{

public class proxy : iSomeCommonInterface
{
    private samsungClass A; //A:iSomeCommonInterface
    private sonyClass B; //A:iSomeCommonInterface

    public proxy()
    {
        if (somecondition) {
            //i'm samsunClass
            _privateGenericProxyClass = new A();
        } else {
            //i'm sony 
            _privateGenericProxyClass = new B();
        }

        _privateGenericProxyClass.Event1 += Handler;
        _privateGenericProxyClass.Event2 += Handler;
        _privateGenericProxyClass.Event3 += Handler;
    }

    public string someProperty { get { return _privateGenericProxyClass.someProperty; } }

    public void someMethod()
    {
        _privateGenericProxyClass.someMethod();            
    }
}
}

Cast test:

//{A : iSomeCommonInterface}
iSomeCommonInterface _privateGenericProxyClass = (iSomeCommonInterface)new A();
System.InvalidCastException: 'Impossible to cast ogbject ot type 'My.Namespace.A' sul tipo 'My.Namespace.iSomeCommonInterface'.' 

Have you some different approach ?

the goal would be something like :

Class proxy : (someCondition ? A : B ) 

with someCondition coming from a config file, or env variable, so i can't use in a Build event but at runtime.





Aucun commentaire:

Enregistrer un commentaire