【问题标题】:Generic two-dimensional matrix Length(0) C#通用二维矩阵 Length(0) C#
【发布时间】:2014-02-09 10:40:46
【问题描述】:

我正在尝试构造一个二维矩阵,其中 T 是数字(整数,浮点十进制),但是当我尝试从二维数组 T[,] 创建构造函数时,它不允许我获取长度( 0)和长度(1),只有长度。然后我需要减去、乘以和添加 Matrix 的实例,但是如果没有二维,我将无法通过它们。 编译器错误:需要方法、委托或事件。谢谢。

using System;
public class Matrix<T>
    where T : struct,
     IComparable<T>, 
     IConvertible, 
     IEquatable<T>, 
     IFormattable
{
    readonly T[,] matr;
    public int rows;

    public int Rows
    {
        get { return rows; }
    }

    public int Cols
    {
        get { return cols; }
    }

    public int cols;

    public Matrix(T[,] table)
    {
        matr = table;
        rows = matr.Length(0);//problem here
        cols = matr.Length(1);//problem here
    }

【问题讨论】:

    标签: c# arrays generics matrix


    【解决方案1】:
    matr.GetLength(0)  // -> Gets first dimension size
    
    matr.GetLength(1)  // -> Gets second dimension size
    

    参考。 Multidimensional Arrays

    【讨论】:

      【解决方案2】:

      不是直接的答案,而是需要考虑的问题:不幸的是,C# 不支持“数字”类型的模板参数。以下内容不会在您的矩阵类中编译:

       public static Matrix<T> Add(Matrix<T> a, Matrix<T> b)
       {
           Matrix<T> ret;
           for(...)
           {
               ret[i, j] = a[i,j] + b[i, j]; // Error: No operator + defined for type T
           }
       }
      

      没有接口可以添加到where 子句中来告诉编译器T 必须支持运算符+。

      据我所知,只有两种方法可以解决这个问题:为 double、float、integer 编写三个完全不同的类,或者使用 dynamic 类型。后者获得最好的代码,但可能会对数学库造成严重的性能影响。

      【讨论】:

      • 感谢您的信息。将使用动态。
      【解决方案3】:
      public class Matrix<T>
          where T : struct, 
              IComparable<T>,
              IConvertible,
              IEquatable<T>,
              IFormattable
      {
          private readonly T[,] matr;
          public int rows;
      
          public int Rows
          {
              get { return rows; }
          }
      
          public int Cols
          {
              get { return cols; }
          }
      
          public int cols;
      
          public Matrix(T[,] table)
          {
              matr = table;
              rows = matr.GetLength(0);
              cols = matr.GetLength(1);
          }
      

      【讨论】:

      • 添加一些解释而不是仅提取代码会更有帮助。
      • 迟到 10 分钟有点太晚了,除非你能带来更多答案
      • 米奇小麦完美回答了这个问题。
      猜你喜欢
      • 2014-11-24
      • 1970-01-01
      • 2013-06-19
      • 2021-08-14
      • 2016-03-10
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多