[英]Setting Values Using Reflection
我正在使用VB.NET。 我創建了一個小規模的測試項目,其工作原理與我的程序相似。 我想說些類似的東西:getObjectType(object1)如果Object1.getType()=“ ThisType”然后獲取屬性。 每個對象都包含一個ID,我想這樣做:Object1.Id = -1(我知道它不會那么短或容易)。 我認為有一種方法可以通過使用類似的方法來實現:Object1.SetValue(Value2Change,NewValue),但這不起作用,我不確定如何准確地做到這一點。 下面是我的代碼。 謝謝!
Module Module1
Sub Main()
Dim Db As New Luk_StackUp_ProgramEntities
Dim Obj1 As IEnumerable(Of Stackup) = (From a In Db.Stackups).ToList
Dim Obj2 As IEnumerable(Of Object) = (From a In Db.Stackups).ToList
Dim IdNow As Integer = Obj1(0).IdStackup
Dim StackUpNow As Stackup = (From a In Db.Stackups Where a.IdStackup = IdNow).Single
Console.WriteLine(StackUpNow)
getInfo(StackUpNow)
getInfo(Obj1(0), Obj1(0))
areObjectsSame(Obj1(0), Obj1(67))
switchObjects(Obj1(0), Obj2(1))
getObjectValues(Obj2(55))
Console.WriteLine("========================================")
TestCopyObject(StackUpNow)
ChangeObjectValues(StackUpNow)
Console.ReadKey()
End Sub
Private Sub ChangeObjectValues(Object1 As Object)
Console.WriteLine("Changing Object Values")
Dim myField As PropertyInfo() = Object1.GetType().GetProperties()
'Dim Index As Integer 'Did not find value
'For Index = 0 To myField.Length - 1
' If myField(Index).ToString.Trim = "IdStackup" Then
' Console.WriteLine("Found the ID")
' End If
'Next
If Object1.GetType().Name = "Stackup" Then
'Set the Value
End If
End Sub
好吧,我很難理解您的代碼示例如何應用於您的問題,但是,如果您只是問如何使用反射來設置對象的ID,那么此代碼可能會對您有所幫助。 訣竅在於,通常使用set和get方法來處理屬性。
Imports System.Web.UI.WebControls
Imports System.Reflection
Module Module1
Sub Main()
Dim tb As New Label()
Dim t As Type = tb.GetType()
If TypeOf tb Is Label Then
Dim mi As MethodInfo = t.GetMethod("set_ID")
mi.Invoke(tb, New Object() {"-1"})
End If
Console.WriteLine(tb.ID)
Console.ReadLine()
End Sub
End Module
您可以使用PropertyInfo.SetValue
通過反射設置值。 您還可以使用LINQ SingleOrDefault
查詢來簡化查找正確的PropertyInfo
,因此您可以執行以下操作:
Private Sub ChangeObjectValues(Object1 As Object)
Console.WriteLine("Changing Object Values")
Dim t As Type = Object1.GetType()
If t.Name = "Stackup" Then
Dim myField As PropertyInfo = t.GetProperties() _
.SingleOrDefault(Function(x) x.Name = "IdStackup")
If myField IsNot Nothing Then
Console.WriteLine("Found the ID")
myField.SetValue(Object1, -1)
End If
End If
End Sub
從這個問題尚不清楚,您是否真的需要使用反射-也許可以使用一個公共接口來定義id屬性,或者只是類型檢查和強制轉換等會更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.