我有一个关于foreach行为的问题C#。
我的自定义类实现了一个自定义GetEnumerator. 此方法返回另一个object可隐式转换为string.
但是,如果我这样做foreach(string s in customClass),它会在运行时失败(“无法将 .. 类型的对象转换为字符串”)。
但是,如果我这样做string x = new B(),它就像一个魅力。
注意:这里没有什么特别需要实现的,我只是想了解发生了什么。我对这种非泛型行为特别感兴趣。
有任何想法吗?我缺少什么基础知识?
复制此代码的代码:
public class A : IEnumerable
{
    #region IEnumerable Members
    public IEnumerator GetEnumerator()
    {
        yield return new B();
    }
    #endregion
}
public class B
{
    public static implicit operator string( B b )
    {
        return "to-stringed implicit";
    }
}
// CODE:
A a = new A();
// Works.
B b = new B();
string xxx = b;
// Doesnt work.
foreach( string str in a )
{
}