リフレクションを使用してクラス オブジェクトの型を取得し、特定のクラスにキャストした後に update メソッドを呼び出すことができます。
C# のコード スニペットを使用すると、何をすべきかがわかります。ここobject
で Shared クラスで、オブジェクトを Game1 または Game2 のいずれかのクラスに設定します。次にアクセスし、リフレクションをほとんど使用してオブジェクトを操作するのは実行時です。
public static class GameCommon
{
public static object currentGame;
}
/// .GetType() を使用
GameCommon.currentGame = new Game1();
if (GameCommon.currentGame != null)
{
Type type = GameCommon.currentGame.GetType();
if (type.Name == "Game1")
{
((Game1)GameCommon.currentGame).Update();
}
else if (type.Name == "Game2")
{
((Game2)GameCommon.currentGame).Update();
}
}`
もう1つの最良のアプローチはInterface
ポリモーフィズムであり、IMHOはそれを実装する正しい方法です..
これをチェックして:
public static class GameCommon
{
public static IGame currentGame;
}
public interface IGame
{
void Update();
}
public class Game1 : IGame
{
public void Update()
{
Console.WriteLine("Running:Game1 Updated");
}
}
public class Game2 : IGame
{
public void Update()
{
Console.WriteLine("Running:Game2 Updated");
}
}`
次のように呼び出します。
GameCommon.currentGame = new Game1();
if (GameCommon.currentGame != null)
{
GameCommon.currentGame.Update();
}
GameCommon.currentGame = new Game2();
GameCommon.currentGame.Update();
Console.ReadKey();`
これがあなたを助けることを願っています..