System.Nullable<int> 怎么添加成员
System.Nullable 和 ArrayList是类似的吧? ArrayList 已经可以追加任何类型的变量,又为啥产生个泛型。
我这里用Int试了下,输入“.”符号之后没有“add”函数,不知道这怎么追加变量啊
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections;
namespace Csharp
{
class Program
{
static void Main(string[] args)
{
System.Nullable<int> nullableInt = new System.Nullable<int>();
nullableInt.//这里没有add
Console.WriteLine(nullableInt.Value);
Console.ReadKey();
}
}
}
[解决办法]
nullableInt=int
[解决办法]
null
[解决办法]
单个变量怎么能添加成员?
List<int> nullableInt = new List<int>();
nullableInt.Add(5);
[解决办法]
又不是 集合 ,是可空类型,是值类型
[解决办法]
“Nullable<int>”等价于“int?”
直接赋值即可。
形如:
System.Nullable<int> nullableInt = new System.Nullable<int>();//int? nullableInt;
nullableInt = 1;
nullableInt ++;
等等
[解决办法]
两点
1、他们两个不是一个东西
2、泛型针对于arraylist的优点有,1不用装箱拆箱,提高性能,2类型安全,避免了运行时错误
[解决办法]
public static Nullable<T> Add<T>(this Nullable<T> nullableInt, T value) where T: struct
{
if (nullableInt.HasValue)
{
return nullableInt.Value+value;//不行啊,求指点!!!
}
else
{
return null;
}
}
你可以把所有stuct都写一次
public static Nullable<int> Add(this Nullable<int> nullableInt, int value)
{
if (nullableInt.HasValue)
{
return nullableInt.Value + value;
}
else
{
return null;
}
}
int? abc = 10;
int? cd = abc.Add(1);
Console.WriteLine(cd);//11
[解决办法]
忘记说了
我一直不明白为什么有些人就喜欢把泛型和集合这两个没有一点关联的东西放到一起想问题。
Nullable<T> 是泛型
ArrayList是集合(基本淘汰)
List<T>是泛型集合 List<object>约等于ArrayList
我写的是扩展方法
为什么要使用泛型集合呢,因为C#是强类型语言
ArrayList al;
al.add(1); al.add("a") 没有问题,但读出来呢,比如你存,我读,我就不知道第二个是string类型,al[0]+al[1]报错!!!!!!
List<int> li;只能存int类型的
li.add(1);li.add("a")编译器和VS不让你这样干
[解决办法]
一个通杀的扩展版本 哇咔咔
public static class NullableExtend
{
public static Nullable<T> Add<T>(this Nullable<T> nullableInt, Nullable<T> value) where T : struct
{
if (nullableInt.HasValue)
{
dynamic d1 = nullableInt.Value;
dynamic d2 = value;
return d1 + d2;
}
else
{
return value;
}
}
}
[解决办法]
搞啥子啊,那东西不是集合,而是可空类型。
[解决办法]
确实,一说到泛型马上就有人把List<T>翻出来了