2

コード例:

void Foo(params object[] objects)
{
    var entries = new List<IEntry>();
    foreach(var o in objects)
    {
        var entry = new Entry<o.GetType()>(); // this doesn't work
        entries.Add(entry);
    }

    ...
}

Foo("hello", 5); // should fill entries with Entry<string> and Entry<int>

なぜそれが不可能なのですか?代わりにリフレクションを使用する必要があると思いますか?それを適切かつパフォーマンス的に行う方法は?

4

3 に答える 3

1

次の形式の関数が必要です。

Func<Type, IEntry> 

次のように、静的関数を Foo の親に追加することをお勧めします。

public static IEntry Make(Type type)

その関数内に、自分にとって意味のあるコードを自由に追加してください。

if (type == typeof(string))
{
    return new StringEntry(); //Obviously some special logic based on the type.
}
else
{
    //Default logic
    return (IEntry) Activator.CreateInstance(typeof(Entry<>).MakeGenericType(type));
}
于 2013-09-05T00:58:16.623 に答える