有没有办法让类中的通用字段专门用于构造函数中的特定类型?
例如:
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
,并且它们各自的构造函数将具有不同的签名。
最佳答案
我会重构它以使用依赖注入(inject)。这样,该类就不包含创建它所依赖的其他类的代码,例如 myConcreteField = new ConcreteA<T>(4);
。依赖注入(inject)用于防止代码陷入这样的困境。
(你的例子非常非常抽象,这使得它有点困难。如果你使用像“Concrete”和“Implementation”这样的类名,那么它会使答案更难阅读,因为我们使用这些相同的词来描述概念。 )
无论如何,Concrete
事情是,声明一个接口(interface),例如
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
甚至不知道类是什么 - 它只知道它与接口(interface)匹配。
如果其他类又依赖于更多类,这尤其有用。如果您通过调用 new
创建它们在您的类(class)中,该类(class)必须知道如何创建这些类(class)。
然后,为了连接它,您将使用依赖注入(inject)容器,如 Windsor、Unity、Autofac 等。这在控制台应用程序中并不常见,但我猜这只是实验性的,而不是实际的。
关于c# - 实例化类的通用字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079007/