We use spark to generate HTML-mails. When merging our data into the template I noticed a difference between
<if condition="Equals(#context.UserAccount.Country,'BE')">
<p>You live in Belgium</p>
</if>
<else>
<p>You don't live in Belgium</p>
</else>
and
<if condition="#context.UserAccount.Country == 'BE'">
<p>You live in Belgium</p>
</if>
<开发者_StackOverflow社区else>
<p>You don't live in Belgium</p>
</else>
When I pass in a UserAccount with country set to 'BE' the first one prints correctly 'You live in Belgium', the second one produces the incorrect result.
Can someone tell me why? Can you test on equality of strings without using Equals()?
So the code you posted throws a compiler error when I try to run it. However, the error I get explains why you're seeing different behavior. The error I get his this:
CS0252: Warning as Error: Possible unintended reference comparison;
to get a value comparison, cast the left hand side to type 'string'
Looking at the code that Spark generates, the error and behavior you're seeing makes a lot more sense. First piece of code generates the following comparison:
if (Equals(Eval("context.UserAccount.Country"),"BE"))
I'm pretty sure Eval
returns something of type object
(regardless of what the actual type of the variable is). Then the call to Equals
is probably equivalent to doing this:
Eval("context.UserAccount.Country").Equals("BE")
which then uses the overloaded equals method on the string class (thank you polymorphism) which would return true. Where as the second case:
if (Eval("context.UserAccount.Country") == "BE")
probably just does a reference comparison between two objects, which returns false.
If you don't use the #
before context.UserAccount.Country
, Spark will generate the following code (notice the lack of call to Eval
):
if (context.UserAccount.Country == "BE")
Assuming context
has a UserAccount
property, that has a Country
property of type string then the expression should correctly evaluate to true when Country has the value of "BE".
精彩评论