Generic泛型

网址

https://www.cnblogs.com/dotnet261010/p/9034594.html

Default values

代码:T doc = default;
Now you add a GetDocument method to the DocumentManager class. Inside this method the type T should be assigned to null. However, it is not possible to assign null to generic types. That’s because a generic type can also be instantiated as a value type, and null is allowed only with reference types. To circumvent this problem, you can use the default keyword. With the default keyword, null is assigned to reference types and 0 is assigned to value types.

Queue小知识点

(1)Enqueue():在队列的末端添加元素
(2)Dequeue():在队列的头部读取和删除一个元素。注意,这里读取元素的同时也删除了这个元素,如果队列中不再有任何元素,则会抛出异常。

Constraints泛型约束

即约束T的类型,使T遵循一定的规则,比如T必须继承自某个类,或必须实现某个接口等等。使用where关键字,再加上约束条件。
(详见上述链接)
注:补充
where T: Foo Specifies that type T is required to derive from base class Foo
where T1: T2 With constraints it is also possible to specify that type T1 derives from a generic type T2.
例子:
With a generic type, you can also combine multiple constraints. The constraint where T: IFoo, new() with the MyClass declaration specifies that type T implements the interface IFoo and has a default constructor:
public class MyClass where T: IFoo, new()
{
//coding
}

Inheritance继承

例子:
(1)implements the interface IEnumerable 实现泛型接口
public class LinkedList: IEnumerable
{
//...
}
(2)derived from a generic base class 继承泛型基类
public class Base
{
}
public class Derived: Base
{
}
注:This way, the derived class can be a generic or non-generic class.
For example, you can define an abstract generic base class that is implemented with a concrete type in the derived class. This enables you to write generic specialization for specific types:
public abstract class Calc
{
public abstract T Add(T x, T y);
public abstract T Sub(T x, T y);
}
public class IntCalc: Calc
{
public override int Add(int x, int y) => x + y;
public override int Sub(int x, int y) => x — y;
}
(3) a partial specialization 部分
You can also create a partial specialization, such as deriving the StringQuery class from Query and defining only one of the generic parameters, for example, a string for TResult. For instantiating the StringQuery, you need only to supply the type for TRequest:
public class Query
{
}
public class StringQuery : Query
{
}

Covariance and Contra-Variance 协变和逆变

(1)适用范围:泛型接口和泛型委托
generic interfaces and generic delegates
(2)out : type T is allowed only with return types只返回
in:only allowed to use generic type T as input to its methods只传参

GENERIC STRUCTS结构体泛型

(1)Similar to classes, structs can be generic as well. They are very similar to generic classes with the exception of inheritance features.
(2)public struct Nullable where T: struct
{
//coding
}
(3)

你可能感兴趣的:(Generic泛型)