|
You're welcome!
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Hello !
It's possible to create a list of unknown type at compile time ?
Let's suppose the type is in one variable as a string.
And I want to create a list of this type , and of course after I want to add items from this type to the list.
I have found this code on C# , but it seems not work on vb.net :
Type customList = typeof(List<>).MakeGenericType(tempType);
IList objectList = (IList)Activator.CreateInstance(customList);
object o = objectThatContainsListToCopyFrom;
PropertyInfo p = o.GetType().GetProperty("PropertyName");
IEnumerable copyFrom = p.GetValue(o, null);
foreach(object item in copyFrom) objectList.Add(item);
foreach(object item in objectList) { Debug.WriteLine(item.ToString()); }
I just want to create the list , and after to add items like this :
List1.Items.Add(object).
What can I do ?
Thank you !
|
|
|
|
|
That looks like it should work in C#. What problem do you have with the VB-translation?
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
I don't know c# , so I have used a code translator.
this is the code :
Dim customList As Type = GetType(List(Of )).MakeGenericType(tempType)
Dim objectList As IList = CType(Activator.CreateInstance(customList), IList)
' Copy items from a PropertyInfo list to the object just created
Dim o As Object = objectThatContainsListToCopyFrom
Dim p As PropertyInfo = o.[GetType]().GetProperty("PropertyName")
Dim copyFrom As IEnumerable = p.GetValue(o, Nothing)
For Each item As Object In copyFrom
objectList.Add(item)
Next
' Will throw exceptions if the types don't match.
' Iterate and access the items of "objectList"
' (objectList declared above as non-generic IEnumerable)
For Each item As Object In objectList
Debug.WriteLine(item.ToString())
Next
It shows several errors , but the first is on second line :
Error 103 Too few type arguments to 'System.Collections.Generic.IList(Of T)'
|
|
|
|
|
This works for me:
Option Explicit On
Option Strict On
Imports System.Reflection
Module Module1
Public Class ChildClass
End Class
Public Class SomeClass
Public Property Children As ICollection(Of ChildClass) = New HashSet(Of ChildClass)
End Class
Sub Main()
Dim tempType = GetType(ChildClass)
Dim someClass = New SomeClass
someClass.Children.Add(New ChildClass)
Dim customList As Type = GetType(List(Of )).MakeGenericType(tempType)
Dim objectList As IList = CType(Activator.CreateInstance(customList), IList)
Dim o As Object = someClass
Dim p As PropertyInfo = o.[GetType]().GetProperty("Children")
Dim copyFrom As IEnumerable = CType(p.GetValue(o, Nothing), IEnumerable)
For Each item As Object In copyFrom
objectList.Add(item)
Next
For Each item As Object In objectList
Debug.WriteLine(item.ToString())
Next
End Sub
End Module
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
sorry , but the Ilist type is unknown .
Everytime I get an error that :
Error 103 Too few type arguments to 'System.Collections.Generic.IList(Of T)'
I don't know why ?
|
|
|
|
|
Do you get this error also when running my code on its own in a new console-project?
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Yes , Ilist and Ienumerable are unknown and produce a similar error message that I have posted before.
|
|
|
|
|
I wouldn't know why it should be neccessary for you, as it works for me without, but try it with these imports:
Imports System.Collections
Imports System.Collections.Generic
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
I add :
Imports System.Collections
and now the errors are resolved.
But I have some problems in runtime
- I want first to initialize an empty list.
Because if I have just the :
dim itemlist as Ilist
( Before calling these 2 lines
Dim customList As Type = GetType(List(Of )).MakeGenericType(GetType(MyClass))
itemlist = CType(Activator.CreateInstance(customList), IList)
How can I check if the list is empty or ?? something similar. But I want a general checkin mode , because the same expression must be correct even when I clear the list and I want to check if empty ( before initializing for a new type ).
( I try to use
If itemlist.Count > 0 Then
but doesn't work.
|
|
|
|
|
I have a hard time understanding that - can you explain it a bit more detailed?
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
ok.
I need a way to detect that this list is empty.
But the expression that should do this , must include 2 cases :
- The list is not yet created . ( So it's just declared as mylist as Ilist).
- The list is created ( with your code ) but the items are deleted ( or has no items ).
I try with the code :
If mylist.Count..... but this doesn't work.
|
|
|
|
|
If mylist IsNot Nothing AndAlso mylist.Count > 0 Then
End If
?
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
I need to write some unified language, for example Russian chars along with some extended ascii chars like 'μ' in the same string and send to COM port.
Private WithEvents ObjPriComm As New System.IO.Ports.SerialPort
Dim StrLocSendDataTemp As String = "тестовую строку μg"
If i use "UTF-8"
ObjPriComm.Encoding = System.Text.Encoding.UTF8
ObjPriComm.Write(StrLocSendData)
Output is "тестовую строку Ãμg"
If i use "iso-8859-1"
ObjPriComm.Encoding = System.Text.Encoding.GetEncoding("iso-8859-1")
ObjPriComm.Write(StrLocSendData)
Output is "???????? ?????? μg"
What should be used to get proper output as "тестовую строку μg"??
can anyone help me out to come out of this issue...
modified 15-Apr-15 8:39am.
|
|
|
|
|
This has nothing to do with using the serial port. Characters will only be displayed correctly if you use the right font in the code that displays them to screen or paper.
|
|
|
|
|
I feel font is not a cause...
Even i can able to see what i am getting in serial port monitor or hyper terminal....
To write russian or thai chars i need to encode to utf-8 but utf 8 is not supporting extendted ascii chars.
Actually i want to know the actual encoder to write both chars
Thanks
|
|
|
|
|
A UTF8 character is just a sequence of bytes, so sending them through a serial port does not change them. As I said before it is only when you try to display them that issues may arise, if you use the wrong character set or font.
|
|
|
|
|
Hello !
I'm using entity framework.
I have a situation when I use the function CallByName like this :
For k=0 to I
CallByName(MyObject, "Child1", CallType.Get).ElementAt(k)
......
Next
But I get an error
Public member 'ElementAt' on type 'HashSet(Of Child1) not found. '
But when I use the standart expression
MyObject.Child1.ElementAt(k)
Everything is ok.
Why CallByName return a HashSet(Of Child1) ? And what can I do in my expression in order to get the expected result ?
Thank you !
|
|
|
|
|
A HashSet has no order. It's a set.
|
|
|
|
|
ElementAt(..) is an extension-method and these aren't supported for dynamic typing (which is what you're doing because the return type of CallByName(..) is Object). However, you can either cast the returned object to the actual type and then call the extension method on it:
CType(CallByName(MyObject, "Child1", CallType.Get), HashSet(Of Child1)).ElementAt(k) ..or you can pass the object to Enumerable.ElementAt(..) as a parameter:
Enumerable.ElementAt(CallByName(MyObject, "Child1", CallType.Get), k)
modified 15-Apr-15 5:33am.
|
|
|
|
|
Thank you !
sorry , but if you can understand , I want to use an expression where all are variables. So Myobject is a variable , the navigation property's name is a variable ( a list of strings like "child1" that is filled on runtime ). But if I include a know type like Hashset(of Child1) then I can't realize my goal.
so my final scope is to have a scenario like this :
Dim varobject ------------ ( this will hold an object from Entity ).
Dim l as list(of String)- ( This will hold childs Navigation properties name as string ).
And I want an expression like this :
CallByname(Varobject,l(0),CallType.Get).ElementAt(k)
( of course when this expression will be used , the varobject will be an object from entity , and the list will hold navigation;s properties name that exist on varobject.( I have realized this scenario with count like this : CallByname(Varobject,l(0),CallType.Get).Count , but I don't know hot to realize for the problem I have described )
So for this reason I can't use your solution.
is there any other way I can use ?
Thank you !
|
|
|
|
|
I edited my previous answer, please take a look. The second option should be what you need.
|
|
|
|
|
Thank you !
I don't know if you last solution works correctly, but after I get the element with your code :
Dim element = Enumerable.ElementAt(CallByName(MyObject, "Child1", CallType.Get), k)
I have a code like this :
Public Function CopyEntity(Of T As {Class, New})(ctx As MyEntities, entity As T, Optional copyKeys As Boolean = False) As T
Dim clone As New T()
Dim en = ctx.Entry(clone)
en.State = System.Data.Entity.EntityState.Added
ctx.Entry(clone).CurrentValues.SetValues(entity)
en.State = System.Data.Entity.EntityState.Detached
Return clone
End Function
and I pass the element I get with your code like this :
fhitm = CopyEntity(context, element,False)
I get an error on the line Dim en = ctx.Entry(clone) :
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
Additional information: The entity type Object is not part of the model for the current context.
I thought to using CTypeDynamic in order to cast the element to correct type, but as I wrote , I have only a string "Child1" and I have used :
CTypeDynamic(Element,System.Type.Gettype("Child1")) ,
but the expression
System.Type.Gettype("Child1") always return Nothing.
modified 15-Apr-15 12:49pm.
|
|
|
|
|
This is a bit speculation because I don't have a lot of experience with dynamic typing. But I'm almost sure about it:
Dim element = Enumerable.ElementAt(CallByName(MyObject, "Child1", CallType.Get), k)
Public Function CopyEntity(Of T As {Class, New})(ctx As MyEntities, entity As T, ...) As T
Dim clone As New T()
Dim en = ctx.Entry(clone)
Your options:
1) An ugly if-else-cascade for all potential types of entities where you test for the actual type of the entity and call CopyEntity(..) with an according cast.
2) Reflection. C#-sample here (last time you said you could read it - otherwise please ask):
MethodInfo mi = typeof(CEClass).GetMethod("CopyEntity");
mi = mi.MakeGenericMethod(typeof(MyEntities), element.GetType(), typeof(bool));
object clone = mi.Invoke(CEInstance, new object[] {context, element, false});
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
"REM so "clone" actually is created as just an Object and not of the same type as "element" / "entity"
This is not true because I try to use this instruction :
Ctype(element,Child1)
--- and after that everything works correctly
But as I have explained , I can't use this kind of cast because I don't have the type Child1. I have only the string "Child1".
For that I try to use CTypeDynamic.
So I want to know why this line :
System.Type.Gettype("Child1")
produce Nothing ? Because with default types like "Integer" is working.
|
|
|
|