首页 > 解决方案 > C# create class with conditional operator

问题描述

I know maybe this not a good way to create class but I just wondered why if else working but conditional

operator not and need implicit conversion

static void Main(string[] args)
    {
        dynamic myclass;

        if (true) /*some condition*/
        {
            myclass = new ClassA();
        }
        else
        {
            myclass = new ClassB();
        }

        myclass = true /*some condtion*/ ? new ClassA() : new ClassB();  //this line gives an error

      //Type of conditional expression cannot be determined because there is no implicit conversion between 'ConsoleApp4.ClassA' and 'ConsoleApp4.ClassB'

    }

标签: c#conditional-operatordynamic-class-creation

解决方案


文档

结果和替代的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。


推荐阅读