开发者

Constraints on Type Parameter Clarification please

开发者 https://www.devze.com 2023-03-31 01:27 出处:网络
Could someone p开发者_StackOverflowlease clarify what the code means: public abstract class BaseJobProcessor<T> : JobProcessor where T : BaseQueueMessage{}

Could someone p开发者_StackOverflowlease clarify what the code means:

public abstract class BaseJobProcessor<T> : JobProcessor where T : BaseQueueMessage  {}

Thank you v. much.


public abstract class BaseJobProcessor<T> : JobProcessor where T :  BaseQueueMessage  {}

It's a definition of an abstract generic class that has one type parameter T which is of type BaseQueueMessage . It will cause a compile time error to try to create any instance of a generic class derived from BaseJobProcessor and pass it a type parameter of a type that is not derived from BaseQueueMessage.

This is usually done so you can make some assumptions for T within the code of the BaseJobProcessor class, in this example it would allow to use all public methods and properties defined on BaseQueueMessage on all instances of type T that are created/accessed within BaseJobProcessor<T>. (If you didn't have the constraint you would only be able to use object method/properties on any instance of type T)


It means that any type that fills the position of T must be either BaseQueueMessage itself, or a class derived from it.

So you can say

public class MyQueueMessage : BaseQueueMessage { ... }

public class MyJobProcessor<T> : BaseJobProcessor<T> where T : BaseQueueMessage { ... }

MyJobProcessor<MyQueueMessage> jobProcessor = ...

But you can't say

MyJobProcessor<string> jobProcessor = 

Because string is not derived from BaseQueueMessage

0

精彩评论

暂无评论...
验证码 换一张
取 消