【问题标题】:How to pass a function as an object instead of a function?如何将函数作为对象而不是函数传递?
【发布时间】:2011-12-20 15:12:43
【问题描述】:

我正在尝试为 register 属性方法提供默认值。这需要一个函数,但作为对象(委托?)传递。代码如下:

protected static propertydata registerproperty(string name, Type type, Func<object> createDefaultValue)
{
    return RegisterProperty(name, type, createDefaultValue, false, null);
}

我想调用该 registerproperty 方法,但我不知道如何在 VB.net 中做到这一点。我只需要传递一个新的 Person 对象,我认为这是要走的路:

Public Shared ReadOnly ItemsProperty As PropertyData = RegisterProperty("Items", GetType(IEnumerable(Of Person)), Function() new Person())

这是一个作为函数传递的函数,但我需要它作为对象传递。

对此有什么想法吗?

【问题讨论】:

  • 使用AddressOf 运算符。 documentation on VB delegates 包含许多示例。
  • 代码大致正确,lambda 是Func&lt;object&gt; 的适当替代品。记录您使用的 Visual Studio 版本。
  • [off-topic] 很高兴在 SO 见到 Raymond。
  • 实际问题是有 2 个重载,一个接受 Func,一个接受 TValue。在 C# 中,运行时知道要使用哪个重载(使用 () => new Person() 时,它将使用 Func 重载,否则将使用 TValue 重载)。但是,在 VB.NET 中,它总是使用 TValue 重载。如果有办法将 TDefaultValue 转换为 Func,问题就解决了。

标签: c# vb.net function object


【解决方案1】:

有时,使用 sub 而不是函数可以解决问题,我们已经通过这种方式解决了一些问题。

Public Shared ReadOnly ItemsProperty As PropertyData = RegisterProperty("Items", GetType(IEnumerable(Of Person)), Sub() new Person())

【讨论】:

    【解决方案2】:

    这应该适用于旧版本的框架:

    Public Shared Function whatever() As propertyData
        registerproperty("item", GetType(IEnumerable(Of Person)), AddressOf GetObject)
    End Function
    
    Public Shared Function GetObject() As Person
        return New Person
    End Function
    

    使用 VB 2008 或更高版本,您可以使用现有的:

    registerproperty("Item", GetType(IEnumerable(Of Person)), Function() New Person)
    

    【讨论】:

    • Lambdas 是一种语言特性(VB 2008 aka VB9 以及这里的使用方式),而不是框架特性。
    【解决方案3】:

    参数Func&lt;object&gt; createDefaultValue 表示你必须传递一个返回对象的函数。您不必传递对象。

    Function() new Person()是一个lambda表达式,在VB中表示这样一个函数。

    () =&gt; new Person() 在 C# 中是一样的。

    当需要默认值时,您的ItemsProperty As PropertyData 会自动调用此函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-17
      • 2018-07-15
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2012-05-30
      • 1970-01-01
      相关资源
      最近更新 更多