只是传递一个类型在C#中的参数 [英] Passing just a type as a parameter in C#

查看:98
本文介绍了只是传递一个类型在C#中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以想像它会是得心应手为我做到这一点:

Hypothetically it'd be handy for me to do this:

foo.GetColumnValues(dm.mainColumn, int)
foo.GetColumnValues(dm.mainColumn, string)

其中GetColumns方法将调用不同方法根据传递的类型里面。

where the GetColumns method will call a different method inside depending on the type passed.

是的,我能做到这一点作为一个布尔标志或类似的,我只是想知道是否有一种方法,也许通过这一点,然后问:

Yes, I could do it as a boolean flag or similar, I just wondered if there was a way to perhaps pass this, and then ask:

typeof运算(ARG [1])或类似的...

typeof(arg[1]) or similar...

我可以还覆盖的方法,使用泛型,等等 - 我知道有不同的方法来做到这一点,我只是好奇,如果这是可能的

推荐答案

有两种常用的方法。首先,你可以通过的System.Type

There are two common approaches. First, you can pass System.Type

object GetColumnValue(string columnName, Type type)
{
    // Here, you can check specific types, as needed:

    if (type == typeof(int)) { // ...

这将被称为像这样: INT VAL =(int)的GetColumnValue(COLUMNNAME的typeof(INT));

另一种选择是使用泛型:

The other option would be to use generics:

T GetColumnValue<T>(string columnName)
{
    // If you need the type, you can use typeof(T)...

这是避免拳击,并提供某种类型安全的优势,会被称为像这样: INT VAL = GetColumnValue< INT>(COLUMNNAME);

This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);

这篇关于只是传递一个类型在C#中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆