sách gpt4 ăn đã đi

c# - 应用于通用枚举集合的 Cast.Cast 导致无效的转换异常

In lại 作者:太空狗 更新时间:2023-10-29 20:27:41 27 4
mua khóa gpt4 giày nike

enum Gender { Male, Female }

var k = new[] { Gender.Male }.Cast().ToList().Cast().ToList(); //alright

var p = new[] { Gender.Male }.Cast().Cast().ToList(); //InvalidCastException

第二种情况的原因是什么?我知道我不能投盒装 liệt kêint?直接,但我做了两阶段类型转换,即Cast.Cast这应该有效。

biên tập:

考虑到以下工作,这是令人惊讶的:

object o = Gender.Male;
int i = (int)o; // so here the cast is not to an entirely different type, which works

câu trả lời hay nhất

好的我来查原因了,还是很奇怪。我应该检查一下 Cast我自己首先实现!

这就是Cast已实现:

public static IEnumerable Cast(this IEnumerable source)
{
IEnumerable enumerable = source as IEnumerable;
if (enumerable != null)
{
return enumerable; // this is the culprit..
}
if (source == null)
{
throw Error.ArgumentNull("source");
}
return Enumerable.CastIterator(source);
}

private static IEnumerable CastIterator(IEnumerable source)
{
foreach (object current in source)
{
yield return (TResult)((object)current);
}
yield break;
}

现在问题出在Đầu tiên CastGọi:

new[] { Gender.Male }.Cast()

在这里source as IEnumerableTRONG nguồnĐúngnew[] { Gender.Male }TResultĐúngsố nguyên 在泛型方法中 返回一个非空值(这基本上意味着( new[] { Gender.Male } 在泛型上下文中是一个 IEnumerable),因此它返回相同的可枚举返回 Gender[] ,并且在下一个 Cast 调用,执行实际转换,从 Gender đến int? 失败。至于为什么在通用上下文中发生这种情况,catch it in this question

关于c# - 应用于通用枚举集合的 Cast.Cast 导致无效的转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20292623/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress