- Home /
How can I make a generic class convertible in type?
If I have a generic class:
class Collection < G > {
public G[] stuff
}
and I have two other classes, one of which can convert to the other (though more complex than this!)
class Foo {
public Foo( int i ) { myInt = i; }
public int myInt;
}
class Bar {
public Bar( float f ) { myFloat = f; }
public float myFloat;
public static implicit operator Foo( Bar bar ) {
return new Foo( Math.Ceil(bar.myFloat) );
}
}
And I have collections of both:
Collection < G > fooCollection = new Collection < Foo > ();
Collection < G > barCollection = new Collection < Bar > ();
I want to be able to do something like this:
Collection < G > fooCollection2 = barCollection.Convert( typeof(Foo) );
How would I go about that?
This isn't a Unity-related question. I suggest asking this on a more general program$$anonymous$$g board, like Stack Overflow.
Oh right. Thanks, I've done that. Still, if anyone's got an answer here it'd be much appreciated.
Answer by Julien-Lynge · Jan 30, 2013 at 05:26 PM
Could you define an implicit or explicit conversion?
http://msdn.microsoft.com/en-us/library/z5z9kes2%28v=vs.71%29.aspx
Otherwise, you may just have to define a Convert method as in your example, though you'd probably need to define it as Convert< T >()
- I don't remember offhand if you can pass types as arguments.
You can pass types as arguments. Do you mean add a Convert method to the Collection class, or to the Bar class? On StackOverflow someone suggested this:
Collection<Foo> fooCollection = new Collection<Foo> { stuff = barCollection.stuff.Select(bar => (Foo)bar).ToArray() };
But I don't think that's available in .NET 2.0, is it?
Sure, lambda expressions and LINQ can be used in Unity. Used it alot even on Android and iOS ;)
FanTASTic! Do you mean they can be used straight out of the box, no messing around? Someone on StackOverflow said I would need LINQBridge...
Your answer
Follow this Question
Related Questions
Convert a Java open source project to Unity C#? 1 Answer
Error after converting Jscript to C# 1 Answer
Error CS1061, help 1 Answer
I cant open any scripts. 0 Answers