如何使用泛型将参数传递给非泛型方法?

编程入门 行业动态 更新时间:2024-10-27 06:22:38
本文介绍了如何使用泛型将参数传递给非泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么下面的代码不能编译? 如何根据泛型类型是int,bool,char等创建一个泛型方法来调用相应的BitConverter.GetBytes重载? 更一般地说,我怎样才能创建一个通用的方法来调用基于泛型参数类型的非泛型方法?

使用系统; public class Test { public static void Main() { var f = new Foo(); f.GetBytes(10); //应该调用BitConverter.GetBytes(int); f.GetBytes(true); //应该调用BitConverter.GetBytes(bool); f.GetBytes('A'); //应该调用BitConverter.GetBytes(char); } } public class Foo { public byte [] GetBytes< TSource> (TSource输入) { BitConverter.GetBytes(input); $ div $解析方案

更一般地说,我如何创建一个通用方法来调用基于泛型参数类型的非泛型方法?

一般来说,除非所涉及的方法以 System.Object 作为参数,否则不能。问题在于泛型并不仅限于方法调用参数所允许的类型。

最接近的是使用运行时绑定:

public byte [] GetBytes< TSource> (TSource输入) { dynamic obj = input; BitConverter.GetBytes(obj); $ b

这会将方法绑定逻辑推送到运行时,请拨打适当的方式。

Why does the following code not compile? How can I create a generic method which calls the appropriate "BitConverter.GetBytes" overload based on if the generic type is an "int", "bool", "char", etc.? More generally, how can I create a generic method which calls a non-generic method based on the generic parameter's type?

using System; public class Test { public static void Main() { var f = new Foo(); f.GetBytes(10); // should call BitConverter.GetBytes(int); f.GetBytes(true); // should call BitConverter.GetBytes(bool); f.GetBytes('A'); // should call BitConverter.GetBytes(char); } } public class Foo { public byte[] GetBytes <TSource> (TSource input) { BitConverter.GetBytes(input); } }

解决方案

More generally, how can I create a generic method which calls a non-generic method based on the generic parameter's type?

In general, you can't, unless the method in question takes System.Object as a parameter. The problem is that the generic isn't constrained to just types that would be allowed by the method call arguments.

The closest you can do is to use runtime binding:

public byte[] GetBytes <TSource> (TSource input) { dynamic obj = input; BitConverter.GetBytes(obj); }

This pushes the method binding logic to runtime, and will throw if there isn't an appropriate method to call.

更多推荐

如何使用泛型将参数传递给非泛型方法?

本文发布于:2023-11-16 17:26:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606346.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   参数   方法   泛型将   非泛型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!