C#-如何在不指定泛型类型的情况下在类型“泛型类”的MainForm类中声明变量

时间:2019-02-16 21:53:08

标签: c# generics abstract-class

我有以下通用类:

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

我有5个实现AutoRegisterAbstract的类(抽象类)。

在我的Main表单(内部局部类MainForm:Form)中,我需要声明一个字段:

AutoRegisterThread<> _currentThread

无需指定通用类型,因为我可以将_currentThread初始化为:

_currentThread=new AutoRegisterThread<implementedClass1> 

_currentThread=new AutoRegisterThread<implementedClass2>

_currentThread:将在整个表单中使用(在许多情况下)

2 个答案:

答案 0 :(得分:0)

在C#中具有通用类时,您必须提供type参数。您可以编写另一个不会通用的类。如果有任何逻辑可以在泛型和非泛型类之间共享,则可以将该逻辑移至另一个新类。

答案 1 :(得分:0)

从非泛型基类继承:

internal abstract class AutoRegisterThreadBase { }

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

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

类型

请注意,如果需要,非泛型父类可以与泛型类具有相同的名称;就您而言,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();
    }
}