2013-03-04 54 views
0

如何获得所需的代码以下工作:隐式类型

class Program { 
     static void Main(string[] args) { 

      List<string> strings = new List<string>(); 
      List<int> ints = new List<int>(); 
      List<char> chars = new List<char>(); 


      Results results = new Results(); 
      Type resultingType = results.ResultingType; 

      if (resultingType == typeof(string)) { 
      strings= results.strings; 
      } 
      if (resultingType == typeof(int)) { 
       ints= results.ints; 
      } 
      if (resultingType == typeof(char)) { 
       chars = results.chars; 
      } 

      //Desired 
      List<resultingType> resultingtypelist = results.ResultsList; // but not allowed 


     }    


    } 

    public class Results { 

     public List<string> strings = new List<string>() { "aaa", "bbb", "ccc" }; 
     public List<int> ints = new List<int>() {1, 2, 3, } ; 
     public List<char> chars = new List<char>() {'a', 'b', 'c' }; 



     public Type ResultingType { 
      get { return typeof(int) ;} //hardcoded demo 


     } 

     //Desired --with accessibility of Lists set to private 
     public List<ResultingType> ResultsList { 

      get { 

       if (ResultingType == typeof(string)) { 
        return strings; 
       } 
       if (ResultingType == typeof(int)) { 
        return ints; //hardcoded demo 
       } 
       if (ResultingType == typeof(char)) { 
        return chars; 
       } 
      } 
     } 
    } 

产生的错误是“‘TestTyping.Results.ResultingType’是‘属性’,但使用像“型'“

回答

2

如果我明白你想要做什么,编译时就不会知道ResultsList的数据类型,所以泛型不可能实现。你必须这样做:

public IList ResultsList 
{ 
    get 
    { 
     if (ResultingType == typeof(string)) 
     { 
      return strings; 
     } 
     if (ResultingType == typeof(int)) 
     { 
      return ints; //hardcoded demo 
     } 
     if (ResultingType == typeof(char)) 
     { 
      return chars; 
     } 

     // not one of the above types 
     return null; 
    } 
}