How do I create a delegate for a .NET property?

后端 未结 6 1832
眼角桃花
眼角桃花 2020-12-02 23:21

I am trying to create a delegate (as a test) for:

Public Overridable ReadOnly Property PropertyName() As String

My intuitive attempt was de

6条回答
  •  旧时难觅i
    2020-12-03 00:14

    Re the problem using AddressOf - if you know the prop-name at compile time, you can (in C#, at least) use an anon-method / lambda:

    Test t = delegate { return e.PropertyName; }; // C# 2.0
    Test t = () => e.PropertyName; // C# 3.0
    

    I'm not a VB expert, but reflector claims this is the same as:

    Dim t As Test = Function 
        Return e.PropertyName
    End Function
    

    Does that work?


    Original answer:

    You create delegates for properties with Delegate.CreateDelegate; this can be open for any instance of the type, of fixed for a single instance - and can be for getter or setter; I'll give an example in C#...

    using System;
    using System.Reflection;
    class Foo
    {
        public string Bar { get; set; }
    }
    class Program
    {
        static void Main()
        {
            PropertyInfo prop = typeof(Foo).GetProperty("Bar");
            Foo foo = new Foo();
    
            // create an open "getter" delegate
            Func getForAnyFoo = (Func)
                Delegate.CreateDelegate(typeof(Func), null,
                    prop.GetGetMethod());
    
            Func getForFixedFoo = (Func)
                Delegate.CreateDelegate(typeof(Func), foo,
                    prop.GetGetMethod());
    
            Action setForAnyFoo = (Action)
                Delegate.CreateDelegate(typeof(Action), null,
                    prop.GetSetMethod());
    
            Action setForFixedFoo = (Action)
                Delegate.CreateDelegate(typeof(Action), foo,
                    prop.GetSetMethod());
    
            setForAnyFoo(foo, "abc");
            Console.WriteLine(getForAnyFoo(foo));
            setForFixedFoo("def");
            Console.WriteLine(getForFixedFoo());
        }
    }
    

提交回复
热议问题