Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
C# Compiler Error
Error CS0115 – ‘function’ : no suitable method found to override
Reason for the Error
You would receive this error when you mark the method as override whereas the compiler could not find method to override.
For example, try compiling the below code snippet.
abstract public class Class1
{
public abstract void Function1();
}
abstract public class Class2
{
override public void Function1()
{
}
}
public class DeveloperPublish
{
public static void Main()
{
}
}
The class2 contains the function Function1 which has the override as keyword but there is no method to override as it doesnot have any base class to inherit from.
Error CS0115 ‘Class2.Function1()’: no suitable method found to override ConsoleApp1 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp1\Program.cs 7 Active
Solution
You can fix it by making sure that you are inheriting the right base class which contains the method to override.
I tried to compile this code but it won’t work, getting this error upon compilation:
Pong\Form1.Designer.cs(14,33,14,40): error CS0115: ‘Pong.Form1.Dispose(bool)’: no suitable method found to override
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
namespace Pong
{
public partial class gameArea : Form
{
PictureBox picBoxPlayer, picBoxAI, picBoxBall;
Timer gameTime; // also the game loop
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
Size sizePlayer = new Size(25, 100);
Size sizeAI = new Size(25, 100);
Size sizeBall = new Size(20, 20);
const int gameTimeInterval = 1;
const int ballStartSpeed = 2;
const int ballIncreaseSpeedRate = 1;
const int ballSpeedLimited = 15;
const int aiOffSetLoops = 15;
int ballSpeedX = ballStartSpeed;
int ballSpeedY = ballStartSpeed;
Random rad;
int aiOffSet;
int aiOffSetCounter;
Dictionary<string, SoundPlayer> sounds;
public gameArea()
{
InitializeComponent();
this.DoubleBuffered = true;
picBoxPlayer = new PictureBox();
picBoxAI = new PictureBox();
picBoxBall = new PictureBox();
gameTime = new Timer();
gameTime.Interval = gameTimeInterval;
gameTime.Tick += new EventHandler(gameTime_Tick);
this.Width = SCREEN_WIDTH;
this.Height = SCREEN_HEIGHT;
this.StartPosition = FormStartPosition.CenterScreen;
this.BackColor = Color.Black;
picBoxPlayer.Size = sizePlayer;
picBoxPlayer.Location = new Point(picBoxPlayer.Width / 2, ClientSize.Height / 2 - picBoxPlayer.Height / 2);
picBoxPlayer.BackColor = Color.Blue;
this.Controls.Add(picBoxPlayer);
picBoxAI.Size = sizeAI;
picBoxAI.Location = new Point(ClientSize.Width - (picBoxAI.Width + picBoxAI.Width / 2), ClientSize.Height / 2 - picBoxPlayer.Height / 2); // TODO: why picBoxPlayer and not picBoxAI?
picBoxAI.BackColor = Color.Red;
this.Controls.Add(picBoxAI);
rad = new Random();
aiOffSet = 0;
aiOffSetCounter = 1;
picBoxBall.Size = sizeBall;
picBoxBall.Location = new Point(ClientSize.Width / 2 - picBoxBall.Width / 2, ClientSize.Height / 2 - picBoxBall.Height / 2);
picBoxBall.BackColor = Color.Green;
this.Controls.Add(picBoxBall);
// Load Sounds
sounds = new Dictionary<string, SoundPlayer>();
for (int k = 1; k <= 10; k++)
{
sounds.Add(String.Format(@"pong{0}", k), new SoundPlayer(String.Format(@"pong{0}.wav", k)));
}
// Start Game loop
gameTime.Enabled = true;
}
void gameTime_Tick(object sender, EventArgs e)
{
picBoxBall.Location = new Point(picBoxBall.Location.X + ballSpeedX, picBoxBall.Location.Y + ballSpeedY);
gameAreaCollosions();
padlleCollision();
playerMovement();
aiMovement();
}
private void iaChangeOffSet()
{
if (aiOffSetCounter >= aiOffSetLoops)
{
aiOffSet = rad.Next(1, picBoxAI.Height + picBoxBall.Height);
aiOffSetCounter = 1;
}
else
{
aiOffSetCounter++;
}
}
private void gameAreaCollosions()
{
if (picBoxBall.Location.Y > ClientSize.Height - picBoxBall.Height || picBoxBall.Location.Y < 0)
{
iaChangeOffSet();
ballSpeedY = -ballSpeedY;
sideCollision();
}
else if (picBoxBall.Location.X > ClientSize.Width)
{
padlleSideCollision();
resetBall();
}
else if (picBoxBall.Location.X < 0)
{
padlleSideCollision();
resetBall();
}
}
private void resetBall()
{
if (ballSpeedX > 0)
ballSpeedX = -ballStartSpeed;
else
ballSpeedX = ballStartSpeed;
if (ballSpeedY > 0)
ballSpeedY = -ballStartSpeed;
else
ballSpeedY = ballStartSpeed;
aiOffSet = 0;
picBoxBall.Location = new Point(ClientSize.Width / 2 - picBoxBall.Width / 2, ClientSize.Height / 2 - picBoxBall.Height / 2);
}
private void playerMovement()
{
if (this.PointToClient(MousePosition).Y >= picBoxPlayer.Height / 2 && this.PointToClient(MousePosition).Y <= ClientSize.Height - picBoxPlayer.Height / 2)
{
int playerX = picBoxPlayer.Width / 2;
int playerY = this.PointToClient(MousePosition).Y - picBoxPlayer.Height / 2;
picBoxPlayer.Location = new Point(playerX, playerY);
}
}
private void aiMovement()
{
int aiX = ClientSize.Width - (picBoxAI.Width + picBoxAI.Width / 2);
int aiY = (picBoxBall.Location.Y - picBoxAI.Height / 2) + aiOffSet;
if (aiY < 0)
aiY = 0;
if (aiY > ClientSize.Height - picBoxAI.Height)
aiY = ClientSize.Height - picBoxAI.Height;
picBoxAI.Location = new Point(aiX, aiY);
}
private void padlleCollision()
{
if (picBoxBall.Bounds.IntersectsWith(picBoxAI.Bounds))
{
picBoxBall.Location = new Point(picBoxAI.Location.X - picBoxBall.Width, picBoxBall.Location.Y);
ballSpeedX = -ballSpeedX;
aiCollision();
}
if (picBoxBall.Bounds.IntersectsWith(picBoxPlayer.Bounds))
{
picBoxBall.Location = new Point(picBoxPlayer.Location.X + picBoxPlayer.Width, picBoxBall.Location.Y);
ballSpeedX = -ballSpeedX;
playerCollision();
}
}
private void playerCollision()
{
sounds["pong1"].Play();
SlowDownBall();
}
private void aiCollision()
{
sounds["pong2"].Play();
SlowDownBall();
}
private void sideCollision()
{
sounds["pong3"].Play();
SpeedUpBall();
}
private void padlleSideCollision()
{
sounds["pong9"].Play();
}
private void SpeedUpBall()
{
if (ballSpeedY > 0)
{
ballSpeedY += ballIncreaseSpeedRate;
if (ballSpeedY >= ballSpeedLimited)
ballSpeedY = ballSpeedLimited;
}
else
{
ballSpeedY -= ballIncreaseSpeedRate;
if (ballSpeedY <= -ballSpeedLimited)
ballSpeedY = -ballSpeedLimited;
}
if (ballSpeedX > 0)
{
ballSpeedX += ballIncreaseSpeedRate;
if (ballSpeedX >= ballSpeedLimited)
ballSpeedX = ballSpeedLimited;
}
else
{
ballSpeedX -= ballIncreaseSpeedRate;
if (ballSpeedX <= -ballSpeedLimited)
ballSpeedX = -ballSpeedLimited;
}
}
private void SlowDownBall()
{
if (ballSpeedY > 0)
{
ballSpeedY -= ballIncreaseSpeedRate;
if (ballSpeedY <= ballStartSpeed)
ballSpeedY = ballStartSpeed;
}
else
{
ballSpeedY += ballIncreaseSpeedRate;
if (ballSpeedY >= -ballStartSpeed)
ballSpeedY = -ballStartSpeed;
}
if (ballSpeedX > 0)
{
ballSpeedX -= ballIncreaseSpeedRate;
if (ballSpeedX <= ballStartSpeed)
ballSpeedX = ballStartSpeed;
}
else
{
ballSpeedX += ballIncreaseSpeedRate;
if (ballSpeedX >= -ballStartSpeed)
ballSpeedX = -ballStartSpeed;
}
}
}
}
Выдают ошибку: Assets\Scripts\Hero.cs(72,26): error CS0115: ‘Hero.GetDamage()’: no suitable method found to override
Фрагмент кода:
public override void GetDamage()
{
lives -= 1;
Debug.Log(lives);
}
А если убрать override вылетают другие ошибки.
-
Вопрос задан
-
324 просмотра
Привет!
Ошибка говорит о том, то оператор override не нашел метода в классе родителе для переопределения. Проверьте имеется ли у вас наследование. Если нет, достаточно будет убрать override, чтобы исправить ошибку.
Наследование в C# выглядит примерно так:
public class A: B
Где B — класс родитель, А класс наследник. Подробнее о наследовании: https://metanit.com/sharp/tutorial/3.7.php
Если же наследование есть, убедитесь, что наследуемый класс видит этот метод. Нужно проверить модификатор доступа. Подробнее о них здесь: https://docs.microsoft.com/ru-ru/dotnet/csharp/lan…
Пригласить эксперта
Начните с перевода «no suitable method found to override»
-
Показать ещё
Загружается…
22 сент. 2023, в 18:03
60000 руб./за проект
22 сент. 2023, в 17:11
5000 руб./за проект
22 сент. 2023, в 17:10
7000 руб./за проект
Минуточку внимания
—— Построение начато: проект: Склад фирмы, Конфигурация: Debug x86 ——
F:\диплом\Склад фирмы\Склад фирмы\Program.cs(18,33): ошибка CS0246: Не удалось найти имя типа или пространства имен «Form1» (пропущена директива using или ссылка на сборку?)
Компиляция завершена — ошибок: 1, предупреждений: 0
Кликните здесь для просмотра всего текста
Построение начато 17.06.2016 1:40:51.
ResolveAssemblyReferences:
Будет создан список исключений профиля TargetFramework.
CoreResGen:
Для всех выходных данных обновления не требуется.
GenerateTargetFrameworkMonikerAttribute:
Целевой объект «GenerateTargetFrameworkMonikerAttribute» пропускается, так как все выходные файлы актуальны по отношению к входным.
CoreCompile:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /platform:x86 /errorreport

СБОЙ построения.
Затраченное время: 00:00:01.10
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========
Теперь пишет вот такую ошибку
Добавлено через 12 минут
—— Построение начато: проект: Склад фирмы, Конфигурация: Debug x86 ——
F:\диплом\Склад фирмы\Склад фирмы\Form1.Designer.cs(3,19): ошибка CS0060: Несовместимость по доступности: доступность базового класса «Склад.Form1» ниже доступности класса «Склад.склад»
F:\диплом\Склад фирмы\Склад фирмы\Form1.cs(13,26): (Связанное местоположение)
F:\диплом\Склад фирмы\Склад фирмы\Form1_2.cs(8,11): (Связанное местоположение)
Компиляция завершена — ошибок: 1, предупреждений: 0
Построение начато 17.06.2016 1:52:22.
Кликните здесь для просмотра всего текста
ResolveAssemblyReferences:
Будет создан список исключений профиля TargetFramework.
CoreResGen:
Для всех выходных данных обновления не требуется.
GenerateTargetFrameworkMonikerAttribute:
Целевой объект «GenerateTargetFrameworkMonikerAttribute» пропускается, так как все выходные файлы актуальны по отношению к входным.
CoreCompile:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /platform:x86 /errorreport

СБОЙ построения.
Затраченное время: 00:00:00.58
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========
Стало выдавать такую ошибку после перезагрузки. Вообще не понимаю что происходит

