|
1 | | -using System.Collections.Generic; |
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
2 | 3 | using System.Linq; |
| 4 | +using System.Linq.Expressions; |
3 | 5 | using System.Runtime.Serialization; |
4 | 6 | using NUnit.Framework; |
5 | 7 | using ServiceStack.Text.Tests.DynamicModels; |
@@ -565,4 +567,49 @@ public void Can_change_ignored_properties() |
565 | 567 | Assert.That(dto.ToJson(), Is.EqualTo("{\"Id\":0,\"JsonIgnoreId\":0}")); |
566 | 568 | } |
567 | 569 | } |
| 570 | + |
| 571 | + public class Test |
| 572 | + { |
| 573 | + public string Name { get; set; } |
| 574 | + } |
| 575 | + |
| 576 | + public class PropertyExpressionTests |
| 577 | + { |
| 578 | + [Test] |
| 579 | + public void Can_call_typed_setter_Expressions() |
| 580 | + { |
| 581 | + var nameProperty = typeof(Test).GetProperty("Name"); |
| 582 | + var setMethod = nameProperty.GetSetMethod(); |
| 583 | + |
| 584 | + var instance = Expression.Parameter(typeof(Test), "i"); |
| 585 | + var argument = Expression.Parameter(typeof(string), "a"); |
| 586 | + |
| 587 | + var setterCall = Expression.Call(instance, setMethod, argument); |
| 588 | + var fn = Expression.Lambda<Action<Test, string>>(setterCall, instance, argument).Compile(); |
| 589 | + |
| 590 | + var test = new Test(); |
| 591 | + fn(test, "Foo"); |
| 592 | + Assert.That(test.Name, Is.EqualTo("Foo")); |
| 593 | + } |
| 594 | + |
| 595 | + [Test] |
| 596 | + public void Can_call_object_setter_Expressions() |
| 597 | + { |
| 598 | + var nameProperty = typeof(Test).GetProperty("Name"); |
| 599 | + |
| 600 | + var instance = Expression.Parameter(typeof(object), "i"); |
| 601 | + var argument = Expression.Parameter(typeof(object), "a"); |
| 602 | + |
| 603 | + var instanceParam = Expression.Convert(instance, nameProperty.ReflectedType()); |
| 604 | + var valueParam = Expression.Convert(argument, nameProperty.PropertyType); |
| 605 | + |
| 606 | + var setterCall = Expression.Call(instanceParam, nameProperty.SetMethod(), valueParam); |
| 607 | + |
| 608 | + var fn = Expression.Lambda<Action<object, object>>(setterCall, instance, argument).Compile(); |
| 609 | + |
| 610 | + var test = new Test(); |
| 611 | + fn(test, "Foo"); |
| 612 | + Assert.That(test.Name, Is.EqualTo("Foo")); |
| 613 | + } |
| 614 | + } |
568 | 615 | } |
0 commit comments