共用方式為


Today's C# quiz - does this compile?

 using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<Inter1> ienum1 = new Class1[] { new Class1() };
        foreach (Class2 c in ienum1)
        {
            Console.WriteLine(c);
        }
    }
}

public interface Inter1 { }
public class Class1 : Inter1 { }
public class Class2 { }

Comments

  • Anonymous
    November 16, 2007
    No, it won't compile. Class2 has no relation to Class1 or Inter1. c has to be either of type Class1 or Inter1 for this to compile.

  • Anonymous
    November 16, 2007
    Why is this question so simple? I was expecting questions that only C# MVPs can solve.

  • Anonymous
    November 16, 2007

csc temp.cs

Microsoft (R) Visual C# 2008 Compiler version 3.5.20921 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved.

temp

Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'Class1' to type 'Class2'.   at Program.Main(String[] args) Bonus question - why does it compile?

  • Anonymous
    November 16, 2007
    The comment has been removed

  • Anonymous
    November 16, 2007
    The comment has been removed

  • Anonymous
    November 16, 2007
    using System; using System.Collections.Generic; class Program { static void Main( string [] args) { IEnumerable&lt;Inter1&gt;

  • Anonymous
    November 16, 2007
    The comment has been removed

  • Anonymous
    November 19, 2007
    It compiles because the foreach generates an iterator over types of the interface Inter1 and since the Interface is empty the signature of Class2 matches the interface even though it does not actually implement it.

  • Anonymous
    November 19, 2007
    Good try, but even if you add something to the interface and don't add it to Class2, the code still compiles - you can change the last 3 lines, for instance, to this and it still compiles. public interface Inter1 { int MyProperty { get; } } public class Class1 : Inter1 { public int MyProperty { get { return 0; } } } public class Class2 { }

  • Anonymous
    November 21, 2007
           foreach (Class2 c in ienum1)        {            Console.WriteLine(c);        } is equivalent to in this case to: IEnumerator<Iter1> e = null; try {  e = ienum1.GetEnumerator();  while(e.MoveNext())  {    Class2 instance =  (Class2) e.Current;    Console.WriteLine(instance);  } } finally {  e.Dispose(); } foreach includes an explicit cast.

  • Anonymous
    November 23, 2007
    Got a few good comments to the quiz post , but nobody that commented got it right. I went ahead and sent

  • Anonymous
    November 23, 2007
    Got a few good comments to the quiz post , but nobody that commented got it right. I went ahead and sent