是否有可能改变一个基本数据类型的默认值? [英] Is it possible to change the default value of a primitive data type?

查看:201
本文介绍了是否有可能改变一个基本数据类型的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近创建了一个通用矩阵< T>类充当围绕列表℃的包装;列表与LT; T>>采集。据我所知,这个类可以正常使用。 。我遇到了一个小问题,虽然关于T的默认值



我创建矩阵和LT的实例; INT>(3,3),它创建了一个3×3整数的矩阵,全默认为0使用默认值(T)。我知道,值类型(包括原语),默认为0等价的,并且引用类型默认为null。 ,我想知道0的,如果有可能更改此默认值,这样,如果一个值类型传递到矩阵,将它与5对例如填充来代替。



我试图创造我自己的结构(值类型),但由于不能够使用内部结构参数构造函数,我不能找到一种方法,从0更改为默认值。



我怀疑更改默认值是不可能的,我将不得不通过细胞矩阵电池循环已经被实例化后,但我想在这里问的,以防万一我这样做了。


解决方案

 公共矩阵(INT宽度,诠释高):这个(宽度,高度,默认(T )){} 
公共矩阵(INT宽度,高度INT,T设置defaultValue)
{
名单< T>行=新的List< T>(高度);
的for(int i = 0; I<高度;我++)
{
名单< T>列=新的List< T>(宽);
为(INT J = 0; J<宽度; J ++)
{columns.Add(设置defaultValue); }
rows.Add(列);
}
//店`rows`无论你在内部将其存储。
}



但正如约瑟夫说,有没有设置什么默认(T)计算结果为


I recently created a generic Matrix<T> class that acts as a wrapper around a List<List<T>> collection. As far as I can tell, this class is working perfectly. I am running into a slight problem though regarding the default values of the T's.

I create an instance of Matrix<int>(3, 3), which creates a 3x3 matrix of ints, all defaulted to 0 using default(T). I know that value types (which include primitives) default to a 0 equivalent, and reference types default to null. I was wondering if it was possible to change this default value so that if a value type is passed into the Matrix, it would be populated with 5's for example, instead of 0's.

I tried creating my own struct (value type), but due to not being able to use parameterless constructors inside structs, I cannot find a way to change the default value from 0.

I suspect changing the default value is not possible, and I will have to loop through the Matrix cell by cell after it has been instantiated, but I wanted to ask on here just in case before I do that.

解决方案

 public Matrix(int width, int height) : this(width, height, default(T)) {}
 public Matrix(int width, int height, T defaultValue)
 {
     List<T> rows = new List<T>(height);
     for (int i = 0; i < height; i++)
     {
         List<T> columns = new List<T>(width);
         for (int j = 0; j < width; j++)
         { columns.Add(defaultValue); }
         rows.Add(columns);
     }
     // store `rows` wherever you are storing it internally.
 }

But as Joseph says, there's no way of setting what default(T) evaluates to.

这篇关于是否有可能改变一个基本数据类型的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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