开发者

Ternary operator failing when using reflection

开发者 https://www.devze.com 2023-01-30 07:50 出处:网络
This works: int valueAsInt = 0; if (Int32.TryParse(value, out valueAsInt)) { 开发者_JS百科record.GetType().GetProperty(property).SetValue(record, valueAsInt, null);

This works:

int valueAsInt = 0;

if (Int32.TryParse(value, out valueAsInt))
{
  开发者_JS百科  record.GetType().GetProperty(property).SetValue(record, valueAsInt, null);
}
else
{
    record.GetType().GetProperty(property).SetValue(record, value, null);
}

This, however, does not. Unsure why.

Int32.TryParse(value, out valueAsInt) ? record.GetType().GetProperty(property).SetValue(record, valueAsInt, null) :record.GetType().GetProperty(property).SetValue(record, value, null);

I receive the following error messages:

Error 1 Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Error 2 Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'void'

I was just curious as to why the ternary operator fails in this scenario. Thanks!


Reflection is red herring here. In C#, not all expressions are valid as independent statements. For instance:

a + b;

will not compile.

Similarly, ? : is not a valid expression-statement construct according to C# grammar. You always have to do something with the value of the ternary expression. If you don't care about the value, you should go with an if statement.

Relevant Portion of C# Grammar:

expression-statement:

statement-expression ;

statement-expression:

invocation-expression
object-creation-expression
assignment
post-increment-expression
post-decrement-expression
pre-increment-expression
pre-decrement-expression


The ternary operator expects to return a value. The methods you are calling, I would guess, do not. :)

From the MSDN remarks:

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

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.

If there are no types involved in the execution of your statements (other than void), the ternary operator won't work in this situation.


It's because you're not returning anything from the clause. Ternary operators are used specifically as if/else when the resulting value is to be assigned to some variable or returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消