Istnieją trzy sposoby osiągnięcia tego celu; pierwszym jest użycie GetGetMethod()/GetSetMethod() i utworzenie delegata z Delegate.CreateDelegate. Drugi to lambda (niewiele użyteczne do refleksji!) [Tj. x => x.Foo]. Trzeci to Expression (.NET 3.5).
lambda jest najprostszym ;-P
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());
}
aby pokazać wykorzystania:
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));
pamiętać, że jeśli chcesz delegata skierowaną do konkretnego przykładu, można użyć zamknięć do lambda lub przeciążenie CreateDelegate, które akceptuje i instancja.
Myślę, że to zadziała dla potrzeb, które mam. Dzięki! –
Biorąc pod uwagę, że C# ma być moim pierwszym językiem, naprawdę chciałbym, aby zrozumiałem te rzeczy (tworzenie delegata za pomocą refleksji) - brzmi świetnie – JohnIdol
A dla .net 2.0 można zrobić Działanie valueSetter = delegate (wartość int) {tc .Value = value; } –