我如何创建.NET财产的委托? [英] How do I create a delegate for a .NET property?

查看:67
本文介绍了我如何创建.NET财产的委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个委托(作为测试)为:

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

Public Overridable ReadOnly Property PropertyName() As String

我的直观的尝试宣告委托是这样的:

My intuitive attempt was declaring the delegate like this:

Public Delegate Function Test() As String

和实例是这样的:

Dim t As Test = AddressOf e.PropertyName

但是,这引发错误:

But this throws the error:

方法公众可重写只读属性属性名()作为
  串不具有一个签名
  与代表代表兼容
  功能测试()作为字符串'。

Method 'Public Overridable ReadOnly Property PropertyName() As String' does not have a signature compatible with delegate 'Delegate Function Test() As String'.

,因为我正在处理我尝试这样一个属性:

So because I was dealing with a property I tried this:

Public Delegate Property Test() As String

不过,这将引发编译错误。

But this throws a compiler error.

所以,问题是,我怎么做一个委托财产?

So the question is, how do I make a delegate for a property?

请参阅此链接:

http://peisker.net/dotnet/propertydelegates.htm

推荐答案

重新使用AddressOf问题 - 如果你知道在编译时的道具名称,你可以(在C#中,至少)使用匿名法/λ

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

我不是一个VB的专家,但反射索赔,这是一样的:

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

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

运作的?


原来的答复:

您创建的属性代表们 Delegate.CreateDelegate ;这可以是开放式的任何实例,固定单个实例 - 并可以为getter或setter;我给C的一个例子#...

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<Foo, string> getForAnyFoo = (Func<Foo, string>)
            Delegate.CreateDelegate(typeof(Func<Foo, string>), null,
                prop.GetGetMethod());

        Func<string> getForFixedFoo = (Func<string>)
            Delegate.CreateDelegate(typeof(Func<string>), foo,
                prop.GetGetMethod());

        Action<Foo,string> setForAnyFoo = (Action<Foo,string>)
            Delegate.CreateDelegate(typeof(Action<Foo, string>), null,
                prop.GetSetMethod());

        Action<string> setForFixedFoo = (Action<string>)
            Delegate.CreateDelegate(typeof(Action<string>), foo,
                prop.GetSetMethod());

        setForAnyFoo(foo, "abc");
        Console.WriteLine(getForAnyFoo(foo));
        setForFixedFoo("def");
        Console.WriteLine(getForFixedFoo());
    }
}

这篇关于我如何创建.NET财产的委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆