C# - 如何在主窗体 class 中声明类型为 "Generic Class" 的变量而不指定泛型类型

C# - How can I declare a variable in MainForm class of type "Generic Class" without specifing generic type

我有以下通用 class:

internal class AutoRegisterThread<T> where T: AutoRegisterAbstract
{
field1....
method1...
}

我有 5 个 class 实现了 AutoRegisterAbstract(抽象 class)。

并且在我的主窗体(内部部分 class MainForm : 窗体)中,我需要声明一个字段:

AutoRegisterThread<> _currentThread

没有指定通用类型,因为我可能会启动 _currentThread 为:

_currentThread=new AutoRegisterThread<implementedClass1> 

_currentThread=new AutoRegisterThread<implementedClass2>

_currentThread:将在整个表单中使用(在许多事件中)

当您在 C# 中使用泛型 class 时,您 必须 提供类型参数。您可以编写另一个不通用的 class。如果有任何逻辑应该在通用和非通用 class 之间共享,您可以将该逻辑移动到另一个新的 class.

从非泛型基础继承 class:

internal abstract class AutoRegisterThreadBase { }

internal class AutoRegisterThread<T> : AutoRegisterThreadBase 
   where T: AutoRegisterAbstract
{
field1....
method1...
}

您的主表单字段现在可以是 AutoRegisterThreadBase

类型

注意,如果需要,非泛型父 class 可以与泛型 class 同名;在你的情况下,AutoRegisterThread

编辑:扩展示例,用法:

internal abstract class AutoRegisterThreadBase { /* Leave empty, or put methods that don't depend on typeof(T) */ }
internal abstract class AutoRegisterAbstract { /* Can have whatever code you need */ }

internal class AutoRegisterThread<T> : AutoRegisterThreadBase
    where T : AutoRegisterAbstract
{
    private int someField;
    public void SomeMethod() { }        
}

internal class AutoRegisterWidget : AutoRegisterAbstract { /* An implementation of AutoRegisterAbstract; put any relevant code here */ }

// A type that stores an AutoRegisterThread<T> (as an AutoRegisterThreadBase)
class SomeType
{
    public AutoRegisterThreadBase MyAutoRegisterThread { get; set; }
}

// Your code that uses/calls the above types
class Program
{        
    static void Main(string[] args)
    {
        var someType = new SomeType();

        // Any sub-class of AutoRegisterThreadBase, including generic classes, is valid
        someType.MyAutoRegisterThread = new AutoRegisterThread<AutoRegisterWidget>();

        // You can then get a local reference to that type 
        // in the code that's created it - since you know the type here
        var localRefToMyAutoRegisterThread = someType.MyAutoRegisterThread as AutoRegisterThread<AutoRegisterWidget>;
        localRefToMyAutoRegisterThread.SomeMethod();
    }
}