Newbie at C# here -
I have a JSON data source that I can query. Depending on the query I issue, that JSON interface can return more than one type of object. eg it could return a list of Customers
, or a list of Vendors
, or a list of Items
, or etc. etc. etc.
All of these objects can inherit from one base class.
Is there a way to have a single C# method able to return a list of variable type?
What about if I'm returning just a single Customer, or a single Vendor. Is there a way to make a single ->get(type, id)
method return any of those object types depending on the type
I pass in?
As AD.Net already said, you can make a generic method.
Something like
public T GetData<T>(String query)
{
T data = //query stuff here
return data;
}
Now, if you want to query with a query that returns a list of Customer
:
var list = GetList<List<Customer>>("customerquery");
To query for a single Vendor:
var v = GetList<Vendor>("vendor query");
Etc etc..
Sounds like you are looking for generics .
public T Get<T>(object id)
{
var type = typeof(T);
// construct your query based on the type
// var queryResult = ...
return JsonLibrary.Parse<T>(queryResult);
}
var customer = Get<Customer>("ben");
var vendors = Get<List<Vendor>>("ben&jerrys");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.