Passing just a type as a parameter in C#

前端 未结 7 798
广开言路
广开言路 2020-11-28 21:21

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

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

where t

7条回答
  •  执笔经年
    2020-11-28 22:11

    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)) { // ...
    

    This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));

    The other option would be to use generics:

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

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

提交回复
热议问题