Why does LINQPad dump enum integer values as strings?

橙三吉。 提交于 2019-12-10 12:33:38

问题


I was using LinqPad to test out some Enum functions and I didn't get integers like I expected when I used .Dump(). Why did the ToList() solve the problem?

void Main()
{
    Enum.GetValues(typeof(Options)).Cast<int>().Dump();
    Enum.GetValues(typeof(Options)).Cast<int>().ToList().Dump();
}

public enum  Options 
{
   Equal,
   LessThan,
   GreaterThan
}


回答1:


Actually, LINQPad is not the culprit here. This is because of an optimization in Enumerable.Cast:

    public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) {
        IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
        if (typedSource != null) return typedSource;
        if (source == null) throw Error.ArgumentNull("source");
        return CastIterator<TResult>(source);
    }

As you can see, if source implements IEnumerable<TResult>, then Cast just returns the source unchanged. In this case, source is of type Option[], which happens to implement IEnumerable<int>, so Cast returns an array of Option, and LINQPad dumps it.

I must admit that it came as a surprise that Option[] can be cast to IEnumerable<int>, but it seems to be the case...



来源:https://stackoverflow.com/questions/23276970/why-does-linqpad-dump-enum-integer-values-as-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!