简体   繁体   中英

Calling an overloaded function by using a generic variable as a parameter

I want to extend the BinaryWriter class to be able to write a list to a stream. I want to do this with multiple types of lists. I set up this generic function as an extension

public static void Write<T>(this BinaryWriter source, IEnumerable<T>items)
{
     foreach (T item in items)
          source.Write(item)//This doesn't work
} 

Is this at all possible? I know write can handle all the built in types. I know there is the ability to constrain T to certain types, but I couldn't do it for int and double.

I only need it to work for ints, doubles, and bytes.

I know there is the ability to constrain T to certain types

Unfortunately, the compiler has no idea that T is one of these types, so it has to complain.

I only need it to work for ints, doubles, and bytes.

You can make three overloads then:

public static void Write(this BinaryWriter source, IEnumerable<int>items) {
    foreach (var item in items)
        source.Write(item);
}
public static void Write(this BinaryWriter source, IEnumerable<double>items) {
    foreach (var item in items)
        source.Write(item);
}
public static void Write(this BinaryWriter source, IEnumerable<byte>items) {
    foreach (var item in items)
        source.Write(item);
}

dasblinkenlight's solution is probably the way to go, but here's an alternative:

public static void Write(this BinaryWriter source, IEnumerable items)
{
     foreach (dynamic item in items)
          source.Write(item); //runtime overload resolution! It works!
}

For more info on dynamic , see the documentation .

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