I'm new to C# and I'm trying to implement a matrix class. I want to have a function at(i,j) which would support setting and getting data ie I would like to be able to use it for both M.at(i,j)=5.0
and if (M.at(i,j)>3.0)
. In C++ I would write it like this:
double& at(i,j) {
return data[i * cols+ j];
}
How would the same function look in C#? I've read some topics like Is it Possible to Return a Reference to a Variable in C#? but I don't want to use a wrapper.
What you're looking for is an indexer :
public class Matrix
{
public double this[int i, int j]
{
get
{
return internalStorage[i, j];
}
set
{
internalStorage[i, j] = value;
}
}
}
And you consume it like this:
var matrix = new Matrix();
if (matrix[i, j] > 3.0)
{
// double at index i, j is bigger than 3.0
}
matrix[i, j] = 5.0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.