如何将函数作为对象而不是函数传递?

时间:2011-12-20 15:12:44

标签: c# vb.net function object

我正在尝试为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())

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

对此有何想法?

3 个答案:

答案 0 :(得分:1)

这甚至适用于旧版本的框架:

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)

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

参数Func<object> createDefaultValue表示您必须传递一个返回对象的函数。您不必传递对象。

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

() => new Person()在C#中是相同的。

当需要默认值时,ItemsProperty As PropertyData会自动调用此功能。

相关问题