开发者

Generic Singleton Façade design pattern

开发者 https://www.devze.com 2022-12-25 20:27 出处:网络
Hi I try write singleton façade pattern with gene开发者_开发问答rics. I have one problem, how can I call method from generic variable.

Hi I try write singleton façade pattern with gene开发者_开发问答rics. I have one problem, how can I call method from generic variable. Something like this:

T1 t1 = new T1();
//call method from t1
t1.Method();

In method SingletonFasadeMethod I have compile error:

Error 1 'T1' does not contain a definition for 'Method' and no extension method 'Method' accepting a first argument of type 'T1' could be found (are you missing a using directive or an assembly reference?)

Any advace? Thank, I am beginner in C#.

All code is here:

namespace GenericSingletonFasade
{
    public interface IMyInterface
    {
        string Method();
    }

    internal class ClassA : IMyInterface
    {

        public string Method() 
        { 
            return " Calling MethodA ";
        }
    }

    internal class ClassB : IMyInterface
    {

        public string Method()
        {
           return " Calling MethodB ";
        }
    }

    internal class ClassC : IMyInterface
    {

        public string Method()
        {
            return "Calling MethodC";
        }
    }

    internal class ClassD : IMyInterface
    {

        public string Method()
        {
            return "Calling MethodD";
        }
    }

    public class SingletonFasade<T1,T2,T3> where T1 : class,new()
                                           where T2 : class,new()
                                           where T3 : class,new() 
    {

        private static T1 t1;
        private static T2 t2;
        private static T3 t3;

        private SingletonFasade() 
        {
            t1 = new T1();
            t2 = new T2();
            t3 = new T3();
        }

        class SingletonCreator 
        {
            static SingletonCreator() { }

            internal static readonly SingletonFasade<T1,T2,T3> uniqueInstace =
                new SingletonFasade<T1,T2,T3>();
        }

        public static SingletonFasade<T1,T2,T3> UniqueInstace
        {
            get { return SingletonCreator.uniqueInstace; }
        }



        public string SingletonFasadeMethod()
        {
            //Problem is here
            return t1.Method() + t2.Method() + t3.Method();
        }

    }


}

I use this for my problem.

public class SingletonFasade<T1, T2, T3>
    where T1 : class, IMyInterface, new()
    where T2 : class, IMyInterface, new()
    where T3 : class, IMyInterface, new() 

{//...}

Is any solution without Interfaces ??


You need to add a Derivation Constraint to your generic in order to get access to the method.

So add to your facade definition something like

 public class SingletonFasade<T1, T2, T3>
   where T1 : class,IMyInterface, new()
   where T2 : class,IMyInterface, new()
   where T3 : class,IMyInterface, new()
 {
0

精彩评论

暂无评论...
验证码 换一张
取 消