naw*_*fal 7 c# enums casting type-conversion
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
Run Code Online (Sandbox Code Playgroud)
第二种情况的原因是什么?我知道我不能投了盒装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
Run Code Online (Sandbox Code Playgroud)
好吧我是来查明原因的,还是很奇怪。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;
}
Run Code Online (Sandbox Code Playgroud)
现在问题出在第一个 Cast<int>
调用上:
new[] { Gender.Male }.Cast<int>()
Run Code Online (Sandbox Code Playgroud)
这里泛型方法中的source as IEnumerable<TResult>
where source
isnew[] { Gender.Male }
和TResult
is返回一个非空值(这基本上意味着 ( is an在泛型上下文中),因此它返回相同的可枚举值 is ,并且在下一次调用中,执行实际的强制转换,其中是 from to失败。至于为什么会在一般上下文中发生这种情况,请在这个问题中抓住它。int
new[] { Gender.Male }
IEnumerable<int>
Gender[]
Cast<int?>
Gender
int?
归档时间: |
|
查看次数: |
178 次 |
最近记录: |