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

C# 如何将函数作为对象而不是函数传递?,c#,vb.net,function,object,C#,Vb.net,Function,Object,我试图给register属性方法一个默认值。这需要一个函数,但作为对象(委托?)传递。代码如下: protected static propertydata registerproperty(string name, Type type, Func<object> createDefaultValue) { return RegisterProperty(name, type, createDefaultValue, false, null); } 这是一个作为函数传递的函

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

protected static propertydata registerproperty(string name, Type type, Func<object> createDefaultValue)
{
    return RegisterProperty(name, type, createDefaultValue, false, null);
}
这是一个作为函数传递的函数,但我需要它作为对象传递


对此有何想法?

即使对于较旧版本的框架,这也应该适用:

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)
参数
Func createDefaultValue
意味着您必须传递一个返回对象的函数。您不必传递对象

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

()=>newperson()
在C#中是相同的


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

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

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

使用
运算符的
地址。包含许多示例。代码大致正确,lambda是
Func
的适当替代品。记录您使用的Visual Studio版本。[主题外]很高兴在SO看到Raymond。实际问题是有两个重载,一个接受Func,另一个接受TValue。在C#中,运行时知道要使用哪个重载(当使用()=>newperson()时,它将使用Func重载,否则将使用TValue重载)。然而,在VB.NET中,它总是使用TValue重载。如果有办法将TDefaultValue强制转换为Func,那么问题就解决了。lambda是一种语言功能(VB 2008又名VB9,在这里使用它的方式)而不是一种框架功能。
Public Shared ReadOnly ItemsProperty As PropertyData = RegisterProperty("Items", GetType(IEnumerable(Of Person)), Sub() new Person())