[英]Accessing a function of a class from a function of another class
我試圖從 MainChar 的 Update 函數訪問 Key 的 Update 函數。 這兩個類都繼承自 Sprite 類。 在 Main Char 我收到錯誤:
非靜態字段、方法或屬性“Key.Update(GameTime, List)”需要對象引用。 我曾嘗試將類型放在參數之前,但出現錯誤:
'GameTime' 是一種在給定上下文中無效的類型,'Sprite' 是一種在給定上下文中無效的類型。
我還嘗試通過執行以下操作來創建 Key 的新實例: Key key = new Key(texture, position); 我再次嘗試將類型放在之前,但剛剛得到: Key 不包含帶有 4 個參數的構造函數,並且它們在給定的上下文中無效。 幫助將被感激。
這個問題與一個沒有解決我的問題的類似問題有關,因為我無法使 Update 或 Key 成為靜態。
public MainChar(Texture2D texture) : base(texture)
{
Scale = 0.1f;
}
public override void Update(GameTime gameTime, List<Sprite> sprites)
{
Move();
foreach (var sprite in sprites)
{
if (sprite == this)
{
continue;
}
if (Velocity.X > 0 && IsTouchingLeft(sprite) || Velocity.X < 0 && IsTouchingRight(sprite))
{
Velocity.X = 0;
}
if (Velocity.Y > 0 && IsTouchingTop(sprite) || Velocity.Y < 0 && IsTouchingBottom(sprite))
{
Velocity.Y = 0;
}
if (sprite.rectangle.Intersects(rectangle))
{
hasDied = true;
}
if (sprite is Key)
{
Key.Update(gameTime, sprites);
}
}
Position += Velocity;
}
public int keyCount;
public Key(Texture2D texture, Vector2 position) : base(texture)
{
Position = position;
Scale = 0.08f;
}
public override void Update(GameTime gameTime, List<Sprite> sprites)
{
foreach (var sprite in sprites)
{
if (sprite is MainChar)
{
if (IsTouchingLeft(sprite) == true || IsTouchingRight(sprite) == true || IsTouchingTop(sprite) == true || IsTouchingBottom(sprite) == true)
{
Position = new Vector2(1000, 1000);
keyCount++;
}
}
}
}
在 MainChar 類的 Update 方法中,在檢查 'sprite' 是否是 Key 類型的對象( if(sprite is Key)
)之后,還需要將 'sprite'(它是Sprite類型的對象)轉換為類型密鑰,例如: ((Key)sprite).Update(gameTime, sprites)
。
Sprite 類大概沒有可調用的 Update 方法 - 這就是您收到錯誤的原因。 'is' 檢查不會自動將其轉換為 Key 類型,因此即使您知道 'sprite' 具有 Key 的實際類型,其聲明的類型仍然是 Sprite。
cmhoequist 的答案看起來不錯,如果您使用支持版本,請嘗試此操作
if (sprite is Key k)
{
k.Update(gameTime, sprites);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.