简体   繁体   English

通过使用泛型变量作为参数来调用重载函数

[英]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. 我想扩展BinaryWriter类,以便能够将列表写入流。 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. 我知道write可以处理所有内置类型。 I know there is the ability to constrain T to certain types, but I couldn't do it for int and double. 我知道有能力将T约束到某些类型,但我无法为int和double执行此操作。

I only need it to work for ints, doubles, and bytes. 我只需要它为int,double和bytes工作。

I know there is the ability to constrain T to certain types 我知道有能力将T约束到某些类型

Unfortunately, the compiler has no idea that T is one of these types, so it has to complain. 不幸的是,编译器不知道T是这些类型之一,所以它必须抱怨。

I only need it to work for ints, doubles, and bytes. 我只需要它为int,double和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: dasblinkenlight的解决方案可能是要走的路,但这里有一个替代方案:

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 . 有关dynamic更多信息,请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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