如何在C#中使用泛型数组方法的泛型扩展 [英] How to use the generic extension for generic array method in C#

查看:87
本文介绍了如何在C#中使用泛型数组方法的泛型扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自己的类,就像我的微软提供的列表泛型类一样。



以下是我的代码:



Hi, I am trying to create my own class like a list generic class provided my microsoft.

below is my code:

namespace OwnGenricClass
{
    class Program
    {
        static void Main(string[] args)
        {
            Owngeneric<int> _test = new Owngeneric<int>();
            _test.addvalue(12);
            _test.addvalue(13);
            _test.addvalue(14);
            _test.addvalue(15);
            _test.addvalue(16);
            _test.extnlenght(); //showing error
            
        }
    }

    public class Owngeneric<T>
    {
        int i = 0;

        public T[] _data = new T[1];

        public void addvalue(T value)
        {
            _data[i] = value;
            i++;
            Array.Resize(ref _data, _data.Length + 1);
        }
    }

    public static class ExtensionMethodsClass
    {
        public static int extnlenght<T>(this T[] entity)
        {            
            return entity.Count();
        }
    }
}





我尝试了什么:



我想从扩展方法中获取我的泛型类型数组的长度。



我已创建,但当我打算使用它显示编译时错误时,它无法识别类型的基础。



What I have tried:

I want to get the length of the my generic type array from the extension method.

I have created but when I am going to use it showing compile time error, Its not able to recognize on the bases of type.

推荐答案

您的扩展程序的行为类型为Owngeneric< t>那就是你需要的这个



Your extension is acting on the type Owngeneric<t> so that's what needs to be your "this"

public static int extnlenght<T>(this Owngeneric<T> entity)
{
    return entity.Count; // We also need to create the Count property
}





接下来你的自定义类需要一种返回计数的方法它拥有的项目,所以你也需要实现它;





Next your custom class needs a way of returning the count of the items it holds, so you need to implement that too;

public class Owngeneric<T>
{
    int i = 0;

    public T[] _data = new T[1];

    public void addvalue(T value)
    {
        _data[i] = value;
        i++;
        Array.Resize(ref _data, _data.Length + 1);
    }

    public int Count
    {
        get
        {
            return _data.Length;
        }
    }
}


阅读这个好答案:c# - 为什么Array不是通用类型? - Stack Overflow [ ^ ]



您最好使用 List< T> 进行收藏。这是一个启动:收藏教程 - C#本地快速入门| Microsoft Docs [ ^ ]
Have a read of this great answer: c# - Why isn't Array a generic type? - Stack Overflow[^]

You would be better off working with List<T> for collections. Here is a starter: Collections tutorial - C# local quickstarts | Microsoft Docs[^]




以上代码建议对我有用。



谢谢你回复家伙,非常感谢。
Hi,
The above code suggestion work for me.

Thank you for you response guys, Its really appreciated.


这篇关于如何在C#中使用泛型数组方法的泛型扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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