Can C# generics have a specific base type?

后端 未结 3 614
猫巷女王i
猫巷女王i 2020-12-13 12:34

Is it possible for a generic interface\'s type to be based on a specific parent class?

For example:

public interface IGenericFace

        
3条回答
  •  清歌不尽
    2020-12-13 13:13

    What your are referring to is called "Generic Constraints". There are numerous constraints that can be put on a generic type.

    Some basic examples are as follows:

    • where T: struct - The type argument must be a value type. Any value type except Nullable - can be specified. See Using Nullable Types (C# Programming Guide) for more information.

    • where T : class - The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

    • where T : new() - The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

    • where T : - The type argument must be or derive from the specified base class.

    • where T : - The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

    • where T : U - The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

    These can also be linked together like this:

    C#

    public class TestClass where T : MyBaseClass, INotifyPropertyChanged, new() { }
    public interface IGenericFace where T : SomeBaseClass
    

    VB

    Public Class TestClass(Of T As {MyBaseClass, INotifyPropertyChanged, New})
    Public Interface IGenericInterface(Of T As SomeBaseClass)
    

提交回复
热议问题