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'是一个'属性',但像'类型'一样使用”

4

1 回答 1

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;
    }
}
于 2013-03-04T23:50:36.663 回答