C # general method

I have a method that receives messages from the msmq queue.

I have 6 different queues in msmq and I like one common method that will receive messages. This work, but I need to write 6 methods for each queue. I would like to make it more general.

public List<QueMessage> getMessagesFromObj1Queue() { List<QueMessage> messageList = new List<QueMessage>(); QueObj1 que = new QueObj1(); while (que.ReceiveAll().Count > 0) { varmessage = que.Receive(new TimeSpan(0, 1, 0)); messageList.Add(message); } return messageList; } 

I have 5 different objects that just extend one abstract class. Below work.

 public List<QueMessage> getMessagesFromObj1Queue<T>(T que) { List<QueMessage> messageList = new List<QueMessage>(); while (que.ReceiveAll().Count > 0) { varmessage = que.Receive(new TimeSpan(0, 1, 0)); messageList.Add(message); } return messageList; } 

Above does not work

How to fix it?

+4
source share
4 answers

If T in your example is some base class that inherits all the objects in the queue , you can simply pass this to the method instead of T :

 public List<QueMessage> getMessagesFromObj1Queue<T>(QueueObjBase que) { ... } 

Otherwise, if a common interface appears that will be implemented by all T , use this as a general constraint:

 public List<QueMessage> getMessagesFromObj1Queue<T>(T que) where T : [yourInterface] { } 

Without a general restriction on T , the compiler has no information to know which method or properties are available, and therefore can only process T as an object - which, of course, the RecieveAll() method does not have.

+5
source

The problem is that you told the C # compiler nothing about the que type, and therefore, it should consider it as an object. You must provide additional information so that it can properly bind the retrieval method.

This can be done by adding a general method to the method. for instance

 public List<QueMessage> getMessagesFromObj1Queue<T>(T que) where T : [InsertBaseTypeOfQues] 
+3
source

Add where contraint to the method and delcare type param to be your base class.

where T: The type argument must be or inferred from the specified base class.

see general type restrictions from msdn

+1
source

Be that as it may, type T does not have a ReceiveAll method. You need to add a constraint so that the compiler knows that the method exists for any instance of T. So, you get:

public List getMessagesFromObj1Queue (T que): where T: XXX

I do not know that MSMQ is enough to know what XXX should be.

+1
source

Source: https://habr.com/ru/post/1311881/


All Articles