How to define a class property with type T

How can I get a property that can accept an object of any type (class) ... something like this?

public class HttpConnectorRequest { public int Id { get; set; } public T RequestObject { get; set; } where T: class public string ResponseData { get; set; } public Exception Exception { get; set; } } 

I am trying to find an alternative for something like this:

 public class HttpConnectorRequest { public int Id { get; set; } public ClassA ClassARequestObject { get; set; } public ClassB ClassBRequestObject { get; set; } public ClassC ClassCRequestObject { get; set; } public string ResponseData { get; set; } public Exception Exception { get; set; } } 
+6
source share
1 answer

This is great - you just need to make it general:

 public class HttpConnectorRequest<T> where T: class { public int Id { get; set; } public T RequestObject { get; set; } public string ResponseData { get; set; } public Exception Exception { get; set; } } 

Then you should write something like:

 var request = new HttpConnectorRequest<string>(); request.RequestObject = "Hello!"; 

Generics is a big topic - MSDN is probably a reasonable starting point, although I suspect you'll want to read about it in a textbook or book at some point. (While my own book, C # in depth, obviously covers generics, many others do too :)

Note that this makes the generic type common. If you want to create only one common property, you are out of luck ... although you could make a general method:

 public class HttpConnectorRequest { // Other members elided public void SetRequestObject<T>(T value) where T : class { ... } public T GetRequestObject<T>() where T : class { ... } } 

It is enough that this will do, it is up to you - remember that someone could write:

 var request = new HttpConnectorRequest(); request.SetRequestObject<string>("Hello"); var button = request.GetRequestObject<Button>(); 
+20
source

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


All Articles