2011-12-20 173 views
1

我想给一个默认值的注册属性方法。这需要一个函数,但作为一个对象传递(委托?)。这里的代码:如何将函数作为对象而不是函数传递?

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()) 

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

对这个有什么想法?

+1

使用'AddressOf'操作。 [VB委托文档](http://msdn.microsoft.com/en-us/library/ms172879.aspx)包含许多示例。 – 2011-12-20 15:38:02

+0

代码大致正确,lambda是'Func '的合适替代品。记录您使用的Visual Studio版本。 – 2011-12-20 16:13:57

+1

[离题]很酷,在SO看到Raymond。 – HardCode 2011-12-20 16:44:38

回答

1

有时,子,而不是功能的工作解决了问题,我们已经解决了一些问题,这些问题的方法。

Public Shared ReadOnly ItemsProperty As PropertyData = RegisterProperty("Items", GetType(IEnumerable(Of Person)), Sub() new Person()) 
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) 
+0

Lambdas是一种语言功能(VB 2008又名VB9,并且在此处使用它的方式)不是框架功能。 – 2011-12-20 17:13:53

+0

感谢您的纠正。编辑。 – Jay 2011-12-20 18:43:51

0

参数Func<object> createDefaultValue意味着你必须通过一个返回对象的函数。你不必传递一个对象。

Function() new Person()是λ表达式,它代表在VB这样的功能。

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

ItemsProperty As PropertyData时,需要一个默认值会自动调用这个函数。

相关问题