有没有一种方法可以在类中具有泛型字段,以专门针对构造函数中的特定类型?
例如:
class concreteClass1
{
private int a;
public concreteClass1( int a)
{
this.a = a;
}
}
class concreteClass2
{
string b;
public concreteClass2(string b)
{
this.b = b;
}
}
class A<T>
{
private T field;
public A(int x)
{
field = new concreteClass1(x); //error here CS0029
}
public A(string y)
{
field = new concreteClass2(y); //error here CS0029
}
}
因此,T
可以是concreteClass1
或concreteClass1
和它们各自的构建函数都会有不同的签名。
我将其重构为使用依赖注入。这样,该类就不会包含用于创建其依赖的其他类的代码myConcreteField = new ConcreteA<T>(4);
。依赖注入用于防止代码陷入像这样的难题中。
(您的示例非常非常抽象,这使它有点困难。如果使用诸如“ Concrete”和“ Implementation”之类的类名,则由于我们使用相同的词来描述概念,因此答案很难理解。)
相反,无论那Concrete
是什么,都声明一个接口,例如
public interface ISomethingThatTheOtherClassNeeds<T>
{
public int MySomething {get;set;}
}
public class SomethingThatTheOtherClassNeeds : ISomethingThatTheOtherClassNeeds<string>
{
public int MySomething {get;set;}
}
然后在您的Implementation
课程中:
class Implementation<T>
{
private readonly ISomethingThatTheOtherClassNeeds<T> _something;
public Implementation(ISomethingThatTheOtherClassNeeds<T> something)
{
_something = something;
}
void DoSomething()
{
Console.Write(_something.MySomething.ToString());
}
}
区别在于,它无需负责创建该类,而直接将其传递给Implementation
构造函数。Implementation
甚至不知道类是什么-它只知道它与接口匹配。
如果这些其他类又依赖于更多类,则这特别有用。如果要通过调用new
类来创建它们,则该类必须知道如何创建这些类。
然后将其连接起来,您将使用诸如Windsor,Unity,Autofac之类的依赖项注入容器。对于控制台应用程序,这并不是很常见,但是我猜测这是实验性的而不是真实的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句