C# 通用单态Faç;ade设计模式
嗨,我试着用泛型编写单体外观模式。我有一个问题,如何从泛型变量调用方法。 大概是这样的:C# 通用单态Faç;ade设计模式,c#,generics,C#,Generics,嗨,我试着用泛型编写单体外观模式。我有一个问题,如何从泛型变量调用方法。 大概是这样的: T1 t1 = new T1(); //call method from t1 t1.Method(); 在方法SingletonFasadeMethod中,我有编译错误: 错误1“T1”不包含“Method”的定义,并且找不到接受类型为“T1”的第一个参数的扩展方法“Method”(是否缺少using指令或程序集引用? 有什么建议吗?谢谢,我是C#的初学者 所有代码都在这里: namespace Gen
T1 t1 = new T1();
//call method from t1
t1.Method();
在方法SingletonFasadeMethod中,我有编译错误:
错误1“T1”不包含“Method”的定义,并且找不到接受类型为“T1”的第一个参数的扩展方法“Method”(是否缺少using指令或程序集引用?
有什么建议吗?谢谢,我是C#的初学者
所有代码都在这里:
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();
}
}
}
命名空间GenericSingletonFasade
{
公共接口IMyInterface
{
字符串方法();
}
内部类ClassA:IMyInterface
{
公共字符串方法()
{
返回“调用MethodA”;
}
}
内部类ClassB:IMyInterface
{
公共字符串方法()
{
返回“调用方法B”;
}
}
内部类ClassC:IMyInterface
{
公共字符串方法()
{
返回“调用MethodC”;
}
}
内部类ClassD:IMyInterface
{
公共字符串方法()
{
返回“Calling MethodD”;
}
}
公共类SingletonFasade,其中T1:class,new()
其中T2:class,new()
其中T3:class,new()
{
私有静态T1;
私人静态T2;
专用静态T3;
私人单间公寓()
{
t1=新的t1();
t2=新的t2();
t3=新的t3();
}
类单音创建者
{
静态SingletonCreator(){}
内部静态只读SingletonFasade UniqueInstance=
新的SingletonFasade();
}
公共静态单音段唯一性
{
获取{return SingletonCreator.uniqueinstance;}
}
公共字符串SingletonFasadeMethod()
{
//问题就在这里
返回t1.Method()+t2.Method()+t3.Method();
}
}
}
我用这个来解决我的问题
public class SingletonFasade<T1, T2, T3>
where T1 : class, IMyInterface, new()
where T2 : class, IMyInterface, new()
where T3 : class, IMyInterface, new()
公共类SingletonFasade
其中T1:class,IMyInterface,new()
其中T2:class,IMyInterface,new()
其中T3:class,IMyInterface,new()
{//…}
有没有没有没有没有接口的解决方案 您需要在泛型中添加一个,以便访问该方法
因此,在外观定义中添加如下内容
public class SingletonFasade<T1, T2, T3>
where T1 : class,IMyInterface, new()
where T2 : class,IMyInterface, new()
where T3 : class,IMyInterface, new()
{
公共类SingletonFasade
其中T1:class,IMyInterface,new()
其中T2:class,IMyInterface,new()
其中T3:class,IMyInterface,new()
{
这当然不能回答您的问题,但它的拼写是:facade,实际上是:facade。我看到您在问题中添加了……您能解释一下为什么不想使用接口吗?