考虑这个人为的,琐碎的例子:
var foo = new byte[] {246, 127};
var bar = foo.Cast<sbyte>();
var baz = new List<sbyte>();
foreach (var sb in bar)
{
baz.Add(sb);
}
foreach (var sb in baz)
{
Console.WriteLine(sb);
}
Run Code Online (Sandbox Code Playgroud)
借助Two's Complement的魔力,将-10和127打印到控制台.到现在为止还挺好.有敏锐眼光的人会看到我正在迭代一个可枚举并将其添加到列表中.听起来像是ToList:
var foo = new byte[] {246, 127};
var bar = foo.Cast<sbyte>();
var baz = bar.ToList();
//Nothing to see here
foreach (var sb in baz)
{
Console.WriteLine(sb);
}
Run Code Online (Sandbox Code Playgroud)
除此之外不起作用.我得到这个例外:
异常类型:System.ArrayTypeMismatchException
消息:无法将源数组类型分配给目标数组类型.
我觉得这个例外非常奇怪,因为
ArrayTypeMismatchException - 我自己也没有对阵列做任何事情.这似乎是一个内部例外.Cast<sbyte>罚款(如在第一个例子)的作品,它使用时的ToArray或ToList问题提出了自己.我的目标是.NET v4 …
有人可以澄清一下C#is关键字.特别是这两个问题:
Q1)第5行; 为什么这会回归真实?
Q2)第7行; 为什么没有施放异常?
public void Test()
{
object intArray = new int[] { -100, -200 };
if (intArray is uint[]) //why does this return true?
{
uint[] uintArray = (uint[])intArray; //why no class cast exception?
for (int x = 0; x < uintArray.Length; x++)
{
Console.Out.WriteLine(uintArray[x]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
MSDN的描述并未澄清情况.它声明is如果满足其中任何一个条件,它将返回true.(http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx>MDSN文章)
expression is not null. expression can be cast to type.
我不相信你可以对int []进行有效的转换为uint [].因为:
A)此代码无法编译:
int[] signed = new int[] { -100 };
uint[] unsigned …Run Code Online (Sandbox Code Playgroud)