来自外部类c#的隐式输入

时间:2013-03-04 23:46:32

标签: c# generics types

如何在下面获得所需的代码:

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'是'属性',但用作'类型'”

1 个答案:

答案 0 :(得分: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;
    }
}