Passing just a type as a parameter in C#

前端 未结 7 792
广开言路
广开言路 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 21:57

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

    Alternatively, you could use a generic method:

    public void GetColumnValues<T>(object mainColumn)
    {
        GetColumnValues(mainColumn, typeof(T));
    }
    

    and you could then use it like:

    foo.GetColumnValues<string>(dm.mainColumn);
    
    0 讨论(0)
  • 2020-11-28 21:58

    You can use an argument of type Type - iow, pass typeof(int). You can also use generics for a (probably more efficient) approach.

    0 讨论(0)
  • 2020-11-28 22:02

    You can pass a type as an argument, but to do so you must use typeof:

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

    The method would need to accept a parameter with type Type.


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

    If you want this behaviour then you should not pass the type as an argument but instead use a type parameter.

    foo.GetColumnValues<int>(dm.mainColumn)
    
    0 讨论(0)
  • 2020-11-28 22:02

    Use generic types !

      class DataExtraction<T>
    {
        DateRangeReport dateRange;
        List<Predicate> predicates;
        List<string> cids;
    
        public DataExtraction( DateRangeReport dateRange,
                               List<Predicate> predicates,
                               List<string> cids)            
    
        {
            this.dateRange = dateRange;
            this.predicates = predicates;
            this.cids = cids;
        }
    }
    

    And call it like this :

      DataExtraction<AdPerformanceRow> extractor = new DataExtraction<AdPerformanceRow>(dates, predicates , cids);
    
    0 讨论(0)
  • 2020-11-28 22:05
    foo.GetColumnValues(dm.mainColumn, typeof(int));
    foo.GetColumnValues(dm.mainColumn, typeof(string));
    

    Or using generics:

    foo.GetColumnValues<int>(dm.mainColumn);
    foo.GetColumnValues<string>(dm.mainColumn);
    
    0 讨论(0)
  • 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<T>(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<int>(columnName);

    0 讨论(0)
提交回复
热议问题