关于泛型类的问题。

frdking 2013-12-12 03:43:00
定义了一个泛型类

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="";
...全文
131 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
frdking 2013-12-12
  • 打赏
  • 举报
回复
楼上让我茅塞顿悟,结贴。
rtdb 2013-12-12
  • 打赏
  • 举报
回复
引用 4 楼 frdking 的回复:
[quote=引用 2 楼 rtdb 的回复:] 你又不是LIST或ARRAY,那来的索引?
泛型类就不能同list一样?用索引访问?[/quote] 你非要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="";
漫天雪飞 2013-12-12
  • 打赏
  • 举报
回复
楼上的说的对
  • 打赏
  • 举报
回复
你都没设索引 class Class1<T> { public T this[int index] { get;set; } }
frdking 2013-12-12
  • 打赏
  • 举报
回复
引用 2 楼 rtdb 的回复:
你又不是LIST或ARRAY,那来的索引?
泛型类就不能同list一样?用索引访问?
sj490790083 2013-12-12
  • 打赏
  • 举报
回复
泛型和可以用下标访问毫无关系,你想这么访问,得定义一个索引器 类似这样
   
       public List<ClassA> lst;
       public ClassA this[int index]
        {
            get
            {                     
               return lst[index];
            }
            set
            {
              lst[index] = value;
           
            }
rtdb 2013-12-12
  • 打赏
  • 举报
回复
你又不是LIST或ARRAY,那来的索引?
zhanglong_longlong 2013-12-12
  • 打赏
  • 举报
回复
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;
            }
        }
    }

110,537

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧