首页 > 解决方案 > 为什么隐式转换在 C# 中不起作用

问题描述

请指出Error1Error2的原因。

Error1是使用接口作为 IList 类型时不执行隐式转换的错误。

Error2是 int 类型在使用带有 IComparable 参数的函数时不执行隐式转换的错误。

class Program
{
    class Test : IComparable
    {
        public int CompareTo(object obj)
        {
            throw new NotImplementedException();
        }
    }

    static void Main(string[] args)
    {
        var testList = new List<Test>();
        var testArr = new Test[]{ };

        FunctionList(testList);//***Error1***
        FunctionArr(testArr);

        var intArr = new int[] {};
        FunctionArr(intArr);//***Error2***
    }

    static void FunctionList(IList<IComparable> comparables)
    {
        //..
    }

    static void FunctionArr(IComparable[] comparables)
    {
        //..
    }
}

标签: c#implicit-conversion

解决方案


推荐阅读