c# - 实例化类的通用字段

标签 c# .net generics constructor field

有没有办法让类中的通用字段专门用于构造函数中的特定类型?

例如:

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 可以是 concreteClass1concreteClass1,并且它们各自的构造函数将具有不同的签名。

最佳答案

我会重构它以使用依赖注入(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/

相关文章:

C# 3.0 - 如何将文件从 MemoryStream 保存到数据库?

c# - Crystal Reports 可以缩放以适合页面吗

c# - 无法让 MFC dll 函数在 .net 中运行

c# - 我如何知道我的应用程序是从 C# 中的控制台还是窗口打开的

c# - 确定哪个列表框的事件已经启动

java - 如何避免通用数组上的 @SuppressWarnings

c# - 如何确定 Validation.ErrorEvent 中是否不再有错误?

c# - 从服务器端线程更新面板

generics - 从 Kotlin 中的通用扩展函数/方法派生函数引用

java - 实现通用接口(interface)时如何避免强制转换