首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于泛型类的有关问题

2013-12-13 
关于泛型类的问题。定义了一个泛型类class Class1T{private string nameprivate int agepublic string

关于泛型类的问题。
定义了一个泛型类


    class Class1<T>
    {
        private string name;
        private int age;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }


    
Class1<string> cs = new Class1<string>();
        实例化以后,怎么没有索引呢? 
        不能以这个方式访问属性 cs[0].Name=""; 
           
[解决办法]
namespace ConsoleApplication13
{
    class Program
    {
      
        static void Main(string[] args)
        {
            new System.Threading.Thread(new System.Threading.ThreadStart(
                 () =>
                 {

                 }
                )).Start();
            C c = new C();
            Console.Write(c["test2"].Name);  
        }
    }

    class A
    {
        private string name;

        public A(string names)
        {
            name = names;
        }
        public string Name
        {
            get{return name;}
        }
    }

    class C
    {
        public Dictionary<string, A> test = new Dictionary<string, A>();

        public C()
        {
            test.Add("test",new A("testValues"));
            test.Add("test2", new A("test2Values"));
        }

        public A this[string key]
        {
            get
            {
                A value = test.Where(q => q.Key == key).Select(q => q.Value).FirstOrDefault();  //get all keys

                return value;
            }
        }
    }


[解决办法]
泛型和可以用下标访问毫无关系,你想这么访问,得定义一个索引器

类似这样
   
       public List<ClassA> lst;
       public ClassA this[int index]
        {
            get
            {                     
               return lst[index];
            }
            set
            {
              lst[index] = value;
           
            }

[解决办法]
引用:
Quote: 引用:

你又不是LIST或ARRAY,那来的索引?

泛型类就不能同list一样?用索引访问?


你非要cs[0].Name=""的话,得这样:

//Class1<string> cs = new Class1<string>();
List<Class1<string>> cs = new List<Class1<string>>();
cs.Add(new Class1<string>());
cs[0].Name=""; 

热点排行