简体   繁体   中英

Polymorphic return type in c#

I have a function that currently prototyped as:

List<object> get_object_list(byte object_type, object_void_delegate get_one_specific_type_object)
{}

As the logic of getting a list of elements is the same for all the types I have, but the logic for getting one element , is different from one type to another , I was hoping to have one function for getting all sort of list ( get_object_list() ).

for example for type Car I would call:

List<Car> cars_list = (List<Car>) get_object_list (CAR , get_one_car);

The problem now is I'm having c compilation error for invalid conversion: cannot convert List<object> to List<Car>

Is there anyway to fix it?

Update: Some clarifications. get_object_list() is in a client component, and it gets it's data from network resource (a NetStream ). object_type is being sent to the server to let it know the desired list type. Server will reply with a Uint32 number_of_items describing the number of elements available. then, get_one_specific_type_object() will be called number_of_items times.

It sounds like you might want to make the method generic:

List<T> GetObjectList<T>(byte objectType, Func<T> singleObjectGetter)

You'd call it as:

List<Car> cars = GetObjectList<Car>(CAR, GetOneCar);

Indeed you may well find that type inference allows you to just write:

List<Car> cars = GetObjectList(CAR, GetOneCar);

It's possible you want something like a Func<int, T> or similar - we can't really tell. It's also not clear what the first parameter is meant to be for, to be honest. If you need more detail than this, you should provide more context.

As a side note, I'd strongly encourage you to embrace C# / .NET naming conventions.

Although I imagine there should be better ways to implement your feature, this should do the trick to make your code work as it is.

List<Car> cars_list =  get_object_list (CAR , get_one_car)
        .Cast<Car>()
        .ToList()

You may think of using IEnumerable.Cast method for this purpose.

A simple example may look like:

    var objectArray = new object[]{1,2,3,4,5,8};
    var intList = objectArray .Cast<int>()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM