本文介绍了从C#转换为VB.NET的代码中出现奇怪的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
While reading an answer I got this code:
public static class Helper
{
public static bool GetAutoScroll(DependencyObject obj)
{
return (bool)obj.GetValue(AutoScrollProperty);
}
public static void SetAutoScroll(DependencyObject obj, bool value)
{
obj.SetValue(AutoScrollProperty, value);
}
public static readonly DependencyProperty AutoScrollProperty =
DependencyProperty.RegisterAttached("AutoScroll", typeof(bool),
typeof(Helper),
new PropertyMetadata(false, AutoScrollPropertyChanged));
private static void AutoScrollPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var scrollViewer = d as ScrollViewer;
if (scrollViewer != null && (bool)e.NewValue)
{
scrollViewer.ScrollToBottom();
}
}
}
Since I work in VB.NET, so I converted it and got:
Public NotInheritable Class Helper
Private Sub New()
End Sub
Public Shared Function GetAutoScroll(ByVal obj As DependencyObject)
As Boolean
Return CBool(obj.GetValue(AutoScrollProperty))
End Function
Public Shared Sub SetAutoScroll(ByVal obj As DependencyObject,
ByVal value As Boolean)
obj.SetValue(AutoScrollProperty, value)
End Sub
Public Shared ReadOnly AutoScrollProperty As DependencyProperty =
DependencyProperty.RegisterAttached("AutoScroll", GetType(Boolean),
GetType(Helper),
New PropertyMetadata(False, AutoScrollPropertyChanged)) // Error Here
Private Shared Sub AutoScrollPropertyChanged(ByVal d As
System.Windows.DependencyObject, ByVal e As
System.Windows.DependencyPropertyChangedEventArgs)
Dim scrollViewer = TryCast(d, ScrollViewer)
If scrollViewer IsNot Nothing AndAlso CBool(e.NewValue) Then
scrollViewer.ScrollToBottom()
End If
End Sub
End Class
But the C# code compiles and works fine, but in VB.NET the code gives an error (marked in code) saying:
What am I missing? The PropertyChangedCallback
delegate is exactly the way it is defined in Object Browser:
Public Delegate Sub PropertyChangedCallback(
ByVal d As System.Windows.DependencyObject, ByVal e As
System.Windows.DependencyPropertyChangedEventArgs)
解决方案
C# has a language feature, that can convert method groups to delegate type. So, instead of:
private void Foo() {}
private void Bar(Action arg) {}
Bar(new Action(Foo));
you can write:
Bar(Foo);
I'm not a VB guy, .Looks like you need AddressOf operator:
New PropertyMetadata(False, AddressOf AutoScrollPropertyChanged)
这篇关于从C#转换为VB.NET的代码中出现奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!