I need to pass to a function an object that is an anonymous type.
The thing I expect that the object contains some properties, say Name(string) and Rang(BO).
Say, I have a query like
Dim query = From city In _container.Cities
From street In city.Streets
Select Name = street.Name, Rang = street.Rang
Distinct
Now, I would like to pass each element of this query to a function.
Is it possible?
Yes, it's possible.
You can use cast by example. Here's a sample:
class CastByExample {
public T Cast<T>(T t, object toCast) {
return (T)toCast;
}
public void M(object o) {
var y = Cast(new { Name = "Name", Range = 0 }, o);
Console.WriteLine(y.Name);
}
public void Test() {
var x = new { Name = "John Doe", Range = 17 };
M(x);
}
}
You can also use reflection.
But really, how is jumping through these hoops easier than just writing a concrete non-anonymous type?
It's not possible to state the type of an anonymous object in VB.Net. However if you're comfortable with Option Strict Off
then you can use late binding. Just have the target method accept the parameter of type Object
Public Sub UseAnonymousObject(ByVal p as Object)
Console.WriteLine(p.Name)
Console.WriteLine(p.Rang)
End Sub
...
For Each current in query
UseAnonymousObject(current)
Next
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With