你要做的是叫做「Factory Pattern」。而不是保存你想要創建的類型的字典有字典保持類來生成你想創建的類型(「工廠」)。
public abstract GenericFactory
{
public abstract GenericClass CreateInstance();
}
public GenericClassSub1Factory : GenericFactory
{
public override GenericClass CreateInstance()
{
return new GenericClassSub1();
}
}
public GenericClassSub2Factory : GenericFactory
{
public override BaseClass CreateInstance()
{
return new GenericClassSub2();
}
}
然後你宣佈你的字典,並使用它,像這樣:
class MyClassFactory
{
Dictionary<uint,GenericFactory> mGenericLibrary = new Dictionary<uint,GenericFactory>();
public void RegisterFactory(uint id, GenericFactory factory)
{
mGenericLibrary[id] = factory;
}
public GenericClass GetNewGenericType(uint id)
{
return mGenericLibrary[id].CreateInstance();
}
}
void Example()
{
var factory = new MyClassFactory();
factory.RegisterFactory(1, new GenericClassSub1Factory());
factory.RegisterFactory(2, new GenericClassSub2Factory());
factory.RegisterFactory(3, new GenericClassSub3Factory());
var item1 = factory.GetNewGenericType(1); //Contains a new GenericClassSub1;
var item2 = factory.GetNewGenericType(2); //Contains a new GenericClassSub2;
var item3 = factory.GetNewGenericType(3); //Contains a new GenericClassSub3;
}
UPDATE:
如果你不想讓人們作出工廠類,你仍然可以做工廠模式,但通過委託來完成,那麼最終用戶需要的代碼少得多才能添加到工廠中。
class MyClassFactory
{
Dictionary<uint,Func<GenericClass>> mGenericLibrary = new Dictionary<uint,Func<GenericClass>>();
public void RegisterFactory(uint id, Func<GenericClass> factory)
{
mGenericLibrary[id] = factory;
}
public GenericClass GetNewGenericType(uint id)
{
//This could be one line, but i think mGenericLibrary[id]() looks too weird.
Func<GenericClass> factory = mGenericLibrary[id];
return factory();
}
}
void Example()
{
var factory = new MyClassFactory();
factory.RegisterFactory(1,() => new GenericClassSub1());
factory.RegisterFactory(2,() => new GenericClassSub2());
factory.RegisterFactory(3,() => new GenericClassSub3());
var item1 = factory.GetNewGenericType(1); //Contains a new GenericClassSub1;
var item2 = factory.GetNewGenericType(2); //Contains a new GenericClassSub2;
var item3 = factory.GetNewGenericType(3); //Contains a new GenericClassSub3;
}
你可以從其他類調用'GetNewGenericType'嗎?它是'公共'。 – rae1
它會不會返回集合中的實際對象而不是新的對象? –
所以你想要返回存儲在給定'id'處的對象類型的新實例嗎?如果是這樣,不管在哪裏調用,GetNewGenericType都不會這樣做。你需要更新這個問題,更清楚地說明你需要什麼。 – rae1