问题
why and how this works in the below code
dynamic x = ( c== 'a') ? new D1() :x= new D2();
but not this
dynamic x = ( c== 'a') ? new D1() : new D2();
Code
class Program
{
static void Main(string[] args)
{
var c = Console.ReadKey().KeyChar;
dynamic x = ( c== 'a') ? new D1() :x= new D2();
x.Print();
Console.ReadKey();
}
}
class D1
{
public void Print()
{
Console.WriteLine("D1");
}
}
class D2
{
public void Print()
{
Console.WriteLine("D2");
}
}
回答1:
This has nothing to do with dynamic. This is because in your case the return type is not the same in case of Else.
If you write this statement instead, you will still get the same error.
var x = (c == 'a') ? new D1() : new D2();
However, if you write the following code you will succeed.
var c = 'd';
int a = 5;
decimal d = 6m;
decimal x = (c == 'a') ? a : d;
If you look at the error that you are getting, it is telling you the same thing.
Type of conditional expression cannot be determined because there is no implicit conversion between 'D1' and 'D2'
And For Ternary Operator
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
来源:https://stackoverflow.com/questions/20995623/dynamic-with-ternary-operator