C#泛型 - 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/767181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:19:21  来源:igfitidea点击:

C# Generics - array?

c#generics

提问by Ivan Prodanov

How to redo the declaration of that C++ template function in C#?

如何在 C# 中重做该 C++ 模板函数的声明?

    template <class type>
void ReadArray(type * array, unsigned short count)
{
    int s = sizeof(type) * count;
    if(index + s > size)
        throw(std::exception("Error 102"));
    memcpy(array, stream + index, s);
    index += s;
}   

When called,it append bytes/word/(type) in the given array by reading a stream(stream) at a specific position(index).

调用时,它通过在特定位置(索引)读取流(流)在给定数组中附加字节/字/(类型)。

I tried to redo the declaration like this,but i get an error

我试图重做这样的声明,但出现错误

    public static T void ReadArray(<T> Array inputarray) // error
    {
        ...
    }

Thanks!

谢谢!

Another conservative question - how to append the bytes into that array(memcpy()),should i use a pointer?

另一个保守的问题 - 如何将字节附加到该数组(memcpy())中,我应该使用指针吗?

采纳答案by Guffa

You use it like this:

你像这样使用它:

public static void ReadArray<T>(T[] inputArray) {
   ...
}

You can use the Array.Copymethod to copy data between arrays.

您可以使用该Array.Copy方法在数组之间复制数据。

Edit:
If you want to make a "blind copy" of data between different data types, e.g. byte array to long array, that's not something that you can do using safe code. You can use the BitConverterclass for example to convert eight bytes from an array into a long. You could also use unsafe code with pointers to do the "blind copy", but you should save that until you actually run into performance problems using safe methods.

编辑:
如果您想在不同数据类型(例如字节数组到长数组)之间进行数据的“盲复制”,则使用安全代码无法做到这一点。BitConverter例如,您可以使用该类将数组中的 8 个字节转换为 long。您也可以使用带有指针的不安全代码来执行“盲复制”,但是您应该保存它,直到您使用安全方法实际遇到性能问题为止。

回答by oscarkuo

public static void ReadArray<T>(T[] inputarray)
    {
        ...
    }

To append to an array you should covert it to a List

要附加到数组,您应该将其转换为列表

List<T> list = new List<T>();
list.AddRange(inputarray);
list.AddRange(anotherArray);