数组vb.net中的ReDim对象
有没有办法做到这一点数组vb.net中的ReDim对象,vb.net,Vb.net,有没有办法做到这一点 public MyDic as new Dictionary(Of string,Object) MyDic.Add("SomeName",new object) ' GetValue is a Extension method and uses dic.TryGetValue(...) ReDim MyDic.GetValue("SomeName") as New DataRow 我试图做的是在运行时定义所需的变量,并将它们作为新定义的类型访问 有可能吗 有没有其他
public MyDic as new Dictionary(Of string,Object)
MyDic.Add("SomeName",new object)
' GetValue is a Extension method and uses dic.TryGetValue(...)
ReDim MyDic.GetValue("SomeName") as New DataRow
我试图做的是在运行时定义所需的变量,并将它们作为新定义的类型访问
有可能吗
有没有其他方法或建议来实现这一点
感谢您抽出时间来编辑
根据你的评论,我正在修改答案。我会留下原件,以防其他人像我最初那样理解你的问题
不能修改方法的返回类型并使其返回到字典。但是,您可以直接在字典中更改项目
Dim stuff As New Dictionary(Of String, Object)
stuff.Add("SomeName", New Object())
' Later, when you have to change it.
stuff("SomeName") = 23 ' If you didn't have "SomeName" as a key, it will be created. Otherwise the value will be changed.
您可以将其包装在扩展方法中,如下所示:
<Extension>
Public Sub SetValue(dic As Dictionary(Of String, Object), valueName As String, value As Object)
If Not dic.ContainsKey(valueName) Then Throw New ArgumentOutOfRangeException ' Or whatever you want to do here
dic(valueName) = value
End Sub
如果没有更多的背景知识,我无法提供更具体的内容。您可以使用它来确定如何处理整数、字符串等
我仍然建议将其制作成
字典(字符串、基类)
或字典(字符串、接口)
使用一些基础,您可以安全地假设您可以使用返回的值做什么。忘记您当前的代码。解释一下你到底想解决什么问题。@A朋友我说了我想做的!!如果理解正确,您想在运行时指定类型吗?@fableous yes,我想这样做,就像我说的,如果可能的话,如果您的对象继承自一个公共基,您可以将字典更改为字典(字符串的)
之一,并且在某种程度上仍然保持它的类型安全。除此之外,您还必须像在这里所做的那样使用Object,并在继续相应操作之前,在从字典中读取它时确定它是什么。您无法在运行时更改变量的类型。我正在尝试执行'stuff.GetValue(“SomeName”)=23'@AliTheOne我已更改了答案。
Dim stuff As New Dictionary(Of String, Object)
stuff.Add("SomeName", 23)
Dim item = stuff.GetValue("SomeName")
If item IsNot Nothing Then
Select Case item.GetType()
Case Is = GetType(String)
Console.WriteLine("String")
Case Is = GetType(Integer)
Console.WriteLine("Integer")
End Select
End If