我制作了一个简单的类来保存用户设置。所有操作都很好,但我想再简化/概括一点,但我在从对象的属性(FormLocation)中获取对象(TestSavedSettings)时遇到了问题。如下面的代码所示,我可以从Form1对象的Location属性中获取它。。。但我无法让它对TestSavedSettings起到同样的作用。FormLocation。
下面的代码是完整的,可以剪切粘贴到一个新的VB Windows窗体应用程序中并运行,它将为每次启动保留窗体位置。
一句话:我如何才能获得用于TestSettings的Object。AddBinding"sn"参数?(正如我成功地为"pn"论点所做的那样?
Imports System.Linq.Expressions
Imports System.Configuration
Imports System.Reflection
Public Class Form1
Private TestSavedSettings As New TestSettings_TestForm
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
TestSavedSettings.AddBinding(Function() Me.Location, Function() TestSavedSettings.FormLocation)
'Below is what I would like to use instead of the version in the line above
' TestSettings.AddBinding(Function() Me.Location, Function() TestSavedSettings.FormLocation)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
TestSavedSettings.Save()
End Sub
End Class
Public Class TestSettings_TestForm : Inherits ApplicationSettingsBase
<UserScopedSettingAttribute()>
Public Property FormLocation() As Point
Get
Return CType(Me(MethodBase.GetCurrentMethod().Name.Remove(0, 4)), Point)
End Get
Set(ByVal value As Point)
Me(MethodBase.GetCurrentMethod().Name.Remove(0, 4)) = value
End Set
End Property
'--This alternative method works, but I'd like to just have one shared version of this in a seperate Class as shown at end
Public Sub AddBinding(Of T, T2)(ByVal pn As Expression(Of Func(Of T)), ByVal sn As Expression(Of Func(Of T2)))
Dim FrmPropertyName As String = DirectCast(pn.Body, MemberExpression).Member.Name
Dim Frm As Form = DirectCast(DirectCast(DirectCast(pn.Body, MemberExpression).Expression, ConstantExpression).Value, Form)
Dim SettingName As String = DirectCast(sn.Body, MemberExpression).Member.Name
Frm.DataBindings.Add(New Binding(FrmPropertyName, Me, SettingName, True, DataSourceUpdateMode.OnPropertyChanged))
End Sub
End Class
Public Class TestSettings
Public Shared Sub AddBinding(Of T, T2)(ByVal pn As Expression(Of Func(Of T)), ByVal sn As Expression(Of Func(Of T2)))
Dim FrmPropertyName As String = DirectCast(pn.Body, MemberExpression).Member.Name
Dim Frm As Form = DirectCast(DirectCast(DirectCast(pn.Body, MemberExpression).Expression, ConstantExpression).Value, Form)
Dim SettingName As String = DirectCast(sn.Body, MemberExpression).Member.Name
'>>>>>Problem is with line below, causes exception, .Expression is actrually returning a FieldExpression not a ConstantExpression,
'but can't cast to that....
Dim Setting As Object = DirectCast(DirectCast(sn.Body, MemberExpression).Expression, ConstantExpression).Value
Frm.DataBindings.Add(New Binding(FrmPropertyName, Setting, SettingName, True, DataSourceUpdateMode.OnPropertyChanged))
End Sub :End Class
实现您想要的功能的一种方法是编译并执行包含所需值的子表达式,而不是尝试手动处理它:
Dim settingExpression = DirectCast(sn.Body, MemberExpression).Expression
Dim setting = Expression.Lambda(Of Func(Of Object))(settingExpression).Compile().Invoke()