C#参数明显的编译器错误(C#5.0) [英] C# params apparent compiler bug (C# 5.0)

查看:91
本文介绍了C#参数明显的编译器错误(C#5.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是

This is a followup on a thread I thought was resolved yesterday. Yesterday I was having problems with my code in the following case:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        class Bar
        {
            int v;

            public Bar(int v) { this.v = v; }
            public override string ToString() { return v.ToString(); }
        }

        static void Main(string[] args)
        {
            Foo(1, 2, 3);
            Foo(new int[] { 1, 2, 3 });
            Foo(new Bar(1), new Bar(2), new Bar(3));
            Foo(new Bar[] { new Bar(1), new Bar(2), new Bar(3) });
            System.Threading.Thread.Sleep(20000);
        }

        static void Foo(params object[] objs)
        {
            Console.WriteLine("New call to Foo: ");
            foreach(object o in objs)
                Console.WriteLine("Type = " + o.GetType() + ", value = "+o.ToString());
        }
    }
}

如果运行此命令,则上次调用Foo可能会出现问题.参数是向量的事实是丢失的".

If you run this you can see a problem with the last call to Foo. The fact that the argument is a vector is "lost".

所以....有人知道如何报告C#编译器错误吗?还是将其视为反射错误?

So.... anyone know how to report a C# compiler bug? Or would this be considered a reflection bug?

(真是令人欣慰:我为自己在这里浪费了自己的错误而感到沮丧.事实上,毕竟这是C#错误,而且我得到了辩护!而且,我们有多少次看到实际的错误?这些天C#编译器有bug吗?不常见...)

(What a relief: I was bummed to think I had wasted time here with a bug of my own. In fact it is a C# bug after all, and I'm vindicated! And how often do we get to see actual C# compiler bugs these days? Not common...)

推荐答案

我希望期望这两个调用具有相同的功能-params参数是被调用方法中的数组.乔恩·斯基特(Jon Skeet)在上一个问题中的示例起作用,因为int的数组与对象数组不协变(因此被视为new Object[] { new Int[] {1,2,3} }),但是在此示例中,FooBars 的数组是 与对象数组协变,因此您的参数将扩展为objs参数.

I would expect these two calls to function identically- a params argument is an array in the called method. Jon Skeet's example in the previous question works because an array of int's is not covariant to an array of objects (and so is treated as new Object[] { new Int[] {1,2,3} }), but in this example an array of FooBars is covariant to an array of objects, and so your parameter is expanded into the objs argument.

万物的维基百科涵盖了这种确切的情况:协方差和协方差(计算机科学)

Wikipedia of all things covers this exact case: Covariance and contravariance (computer science)

对不起,但是我确定这不是编译器错误.

Sorry but I am sure that this is not a compiler bug.

您可以因此实现所需的目标:

You can achieve what you want thus:

Foo(new Object[] { new Bar[] { new Bar(1), new Bar(2), new Bar(3) } });

NEW EDIT(其他作者):

NEW EDIT (other author):

或者简单地使用:

Foo((Object)new Bar[] { new Bar(1), new Bar(2), new Bar(3) });

这篇关于C#参数明显的编译器错误(C#5.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆