enum Gender { Male, Female }
var k = new[] { Gender.Male }.Cast<int>().ToList().Cast<int?>().ToList(); //alright
var p = new[] { Gender.Male }.Cast<int>().Cast<int?>().ToList(); //InvalidCastException
第二种情况是什么原因?我知道我不能直接将盒装转换enum
为int?
,但是我进行两阶段的转换,即Cast<int>.Cast<int?>
应该可以正常工作。
编辑:
考虑到以下工作,这是令人惊讶的:
object o = Gender.Male;
int i = (int)o; // so here the cast is not to an entirely different type, which works
好吧,我来找出原因,这仍然很奇怪。我应该Cast<T>
首先自己检查实施情况!
这是如何Cast<T>
实现的:
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
{
IEnumerable<TResult> enumerable = source as IEnumerable<TResult>;
if (enumerable != null)
{
return enumerable; // this is the culprit..
}
if (source == null)
{
throw Error.ArgumentNull("source");
}
return Enumerable.CastIterator<TResult>(source);
}
private static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
{
foreach (object current in source)
{
yield return (TResult)((object)current);
}
yield break;
}
现在问题出在第一个 Cast<int>
电话上:
new[] { Gender.Male }.Cast<int>()
此处通用方法source as IEnumerable<TResult>
中的source
isnew[] { Gender.Male }
和TResult
is返回一个非null值(这基本上意味着(在通用上下文中是一个)),因此它返回了相同的可枚举值back ,并且在下一次调用中执行了实际的强制转换,是到哪个失败。至于为什么会发生这种情况在一般的情况下,抓住它在这个问题上。int
new[] { Gender.Male }
IEnumerable<int>
Gender[]
Cast<int?>
Gender
int?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句