Generic泛型

2019-02-12  本文已影响0人  津涵

网址

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

Default values

代码:T doc = default;
Now you add a GetDocument method to the DocumentManager<T> 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<T> declaration specifies that type T implements the interface IFoo and has a default constructor:
public class MyClass<T> where T: IFoo, new()
{
//coding
}

Inheritance继承

例子:
(1)implements the interface IEnumerable<T> 实现泛型接口
public class LinkedList<T>: IEnumerable<T>
{
//...
}
(2)derived from a generic base class 继承泛型基类
public class Base<T>
{
}
public class Derived<T>: Base<T>
{
}
注: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<T>
{
public abstract T Add(T x, T y);
public abstract T Sub(T x, T y);
}
public class IntCalc: Calc<int>
{
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<TRequest, TResult>
{
}
public class StringQuery<TRequest> : Query<TRequest, string>
{
}

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<T> where T: struct
{
//coding
}
(3)

上一篇下一篇

猜你喜欢

热点阅读