c# - 在 C# 中仅将类型作为参数传递

标签 c# types methods parameters

假设我这样做会很方便:

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

GetColumns 方法将根据传递的类型在内部调用不同的方法。

是的,我可以把它作为一个 bool 标志或类似的东西,我只是想知道是否有办法传递这个,然后问:

typeof(arg[1]) 或类似的...

我还可以覆盖方法、使用泛型等 - 我知道有不同的方法可以做到这一点,我只是好奇这是否可行。

最佳答案

有两种常见的方法。首先,你可以通过 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));

另一种选择是使用泛型:

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

这具有避免装箱和提供某种类型安全的优点,并且可以这样调用:int val = GetColumnValue<int>(columnName);

关于c# - 在 C# 中仅将类型作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10955579/

相关文章:

haskell - 应用程序中的类型错误 - Haskell?

python - 为什么我第二次运行类方法时会收到 TypeError?

java - 如何使用 Java 主类中创建的对象将值传递给方法

Java 同步静态方法 : lock on object or class

c# - 将数据库表行直接反序列化为 C# 对象 - 是否有这种机制?

iphone - UI键盘类型

c# - 将 html 响应内容的字符集设置为 1252

python - 在python中是否有类似js提升类定义的东西?

c# - 设计推荐 : Lazy init of objects in an array

c# - Window 中的 ViewModel 和 UserControl 中的 ViewModel 之间的 WPF 数据绑定(bind)