2

ジェネリック クラスがある場合:

class Collection < G >  {
    public G[] stuff
}

他に 2 つのクラスがあり、そのうちの 1 つはもう 1 つのクラスに変換できます (ただし、これよりも複雑です!)

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) );
    }
}

そして、私は両方のコレクションを持っています:

Collection < G >  fooCollection = new Collection < Foo > ();
Collection < G >  barCollection = new Collection < Bar > ();

私はこのようなことができるようにしたい:

Collection < G > fooCollection2 = barCollection.Convert( typeof(Foo) );

どうすればそれについて行くでしょうか?

編集: これは Unity 用です。Unity はまだ .NET 2.0 にあると思います。

4

1 に答える 1

3
Collection<Foo> fooCollection = new Collection<Foo> { stuff = barCollection.stuff.Select(bar => (Foo)bar).ToArray() };

必要に応じて、コレクションに拡張メソッドを追加できます。

public static Collection<TResult> Select<TResult, T>(this Collection<T> c, Func<T, TResult> projection)
{
   return new Collection<TResult> { stuff = c.stuff.Select(x => projection(x)).ToArray() };
}

そして、次のように呼び出すことができます。

Collection<Foo> fooCollection2 = barCollection.Select(bar => (Foo)bar);
于 2013-01-30T17:23:55.237 に答える