您好我尝试用泛型编写单例外观模式。我有一个问题,我如何从泛型变量调用方法。 像这样:
T1 t1 = new T1();
//call method from t1
t1.Method();
在方法SingletonFasadeMethod中我有编译错误:
错误1'T1'不包含'Method'的定义,也没有扩展方法'Method'接受类型'T1'的第一个参数(你是否缺少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();
}
}
}
我用这个来解决我的问题。
public class SingletonFasade<T1, T2, T3>
where T1 : class, IMyInterface, new()
where T2 : class, IMyInterface, new()
where T3 : class, IMyInterface, new()
{// ...}
没有接口的解决方案吗?
答案 0 :(得分:2)
您需要在通用名称中添加Derivation Constraint才能访问该方法。
所以添加到您的外观定义类似
public class SingletonFasade<T1, T2, T3>
where T1 : class,IMyInterface, new()
where T2 : class,IMyInterface, new()
where T3 : class,IMyInterface, new()
{