c#中的泛型,并使用索引 [英] Generics in c#, and using index

查看:100
本文介绍了c#中的泛型,并使用索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

T[] str = new T[3];
        int count = 0;

        public void Add(T value)
        {
            if (count < 3)
            {
                str[count] = value;
                count++;
            }
        }

        public T this[int index]
        {
            get
            {
                return str[index];
            }
            set
            {
                str[index] = value;
            }
        }







我尝试上面的程序来成功输出。但我想知道索引在这里使用的目的是什么。如果删除索引属性,我也得到相同的输出。那么什么索引在这里行动???




I try the above program to get output successfully. but i want to know what is the purpose of index is using here. if remove the index property, i also get the same output. so what index acting here???

推荐答案

这取决于你在课堂上提供的功能。

你确实添加了索引器允许通过索引语法访问某些项目,例如
It's up to you what functionality you provide in your classes.
You did add the indexer to allow accessing some items through the means of index syntax, e.g.
MyClass c = ...;
var item = c[2];

如果您不想提供此 Syntactic Sugar [ ^ ],请将它留下。

问候

Andi

If you do not want to provide this Syntactic Sugar[^] in your class, leave it away.
Regards
Andi


索引与泛型无关 - 它只与您声明的数组一起使用: str with is is声明为泛型类型的数组。



如果用标准类型替换代码中的泛型:

The indexing has nothing to do with the generics - it is only being used with the array you declared: str with is declared as an array of the generic type.

If you replace the "generics" in your code with a "standard" type:
int[] str = new int[3];
int count = 0;
public void Add(int value)
{
    if (count < 3)
    {
        str[count] = value;
        count++;
    }
}
public int this[int index]
{
    get
    {
        return str[index];
    }
    set
    {
        str[index] = value;
    }
}

然后它更明显。

这是泛型允许你做的:声明可用于的代码任何类型的数据,同时保持强类型

Then it's more obvious.
And that's what generics allow you do do: declare code that can be used for any type of data, while maintaining strong typing


这篇关于c#中的泛型,并使用索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆