Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TestClass {
- public void SetValue(int value) { Value = value; }
- public int Value { get; set; }
- }
- TestClass tc = new TestClass();
- Action<int> setAction = tc.SetValue;
- setAction.Invoke(12);
- Action<int> valueSetter = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), tc, tc.GetType().GetProperty("Value").GetSetMethod());
- Action<int> valueSetter = v => tc.Value = v;
- class TestClass
- {
- public int Value { get; set; }
- }
- static void Main()
- {
- Func<TestClass, int> lambdaGet = x => x.Value;
- Action<TestClass, int> lambdaSet = (x, val) => x.Value = val;
- var prop = typeof(TestClass).GetProperty("Value");
- Func<TestClass, int> reflGet = (Func<TestClass, int>) Delegate.CreateDelegate(
- typeof(Func<TestClass, int>), prop.GetGetMethod());
- Action<TestClass, int> reflSet = (Action<TestClass, int>)Delegate.CreateDelegate(
- typeof(Action<TestClass, int>), prop.GetSetMethod());
- }
- TestClass foo = new TestClass();
- foo.Value = 1;
- Console.WriteLine("Via property: " + foo.Value);
- lambdaSet(foo, 2);
- Console.WriteLine("Via lambda: " + lambdaGet(foo));
- reflSet(foo, 3);
- Console.WriteLine("Via CreateDelegate: " + reflGet(foo));
- var propertyInfo = typeof (TestClass).GetProperty ("Value");
- var setMethod = property.GetSetMethod (); // This will return a MethodInfo class.
Add Comment
Please, Sign In to add comment