![](/img/trans.png)
[英]Inherit Class1 and implement Interface1 both in case Class1 already implements Interface1
[英]How to fix this ISeries interface implementation in Class1?
我正在從 ISeries 接口的 Setstart(2) 函數開始開發一系列數字。 我試圖在 Class1 中實現這個接口,但它向我拋出了一個錯誤。 我被這個錯誤困住了,無法解決這個問題。 我錯過了什么? 請幫忙
我試圖將接口中的所有函數設為公開 我試圖從接口中刪除公共訪問說明符
public interface ISeries {
void Setstart (int a);
int GetNext ();
void Reset ();
}
class Class1 : ISeries {
int val;
void Setstart (int a) {
val = a;
}
int GetNext () {
return val++;
}
void Reset () {
val = 0;
}
static void Main () {
Class1 c = new Class1 ();
c.Setstart (2);
Console.WriteLine (c.GetNext ());
c.Reset ();
Console.WriteLine ();
}
}
我希望輸出為 3 並且正在生成 0 錯誤
您需要public
您的方法,以便可以從類外部訪問該方法,除了您的代碼看起來不錯之外,還缺少該類。
您需要根據您的場景將所有 3 種方法設為公開,例如:
public void Setstart (int a) {
並且您需要先加 1,然后返回以獲取 3 作為輸出,因為val++
將返回當前值,然后將其增加 1:
public int GetNext () {
// return val++; // Post increment will not work according to question.
val = val + 1;
return val;
}
具有完整接口實現的類將如下所示:
public class Class1 : ISeries {
int val;
public void Setstart (int a) {
val = a;
}
public int GetNext () {
val = val + 1;
return val;
}
public void Reset () {
val = 0;
}
}
你應該嘗試這樣的事情。
因為您必須使用一個變量,所以在這種情況下您必須使用ref
` 關鍵字。
並且您必須將class
中的所有方法標記為public
否則您將無法訪問main
這些方法
代碼:
using System;
namespace StackoverflowProblem
{
public interface ISeries
{
void Setstart(ref int value);
int GetNext(ref int value);
void Reset(ref int value);
}
public class Class1 : ISeries
{
public int val { get; set; }
public void Setstart(ref int value)
{
this.val = value;
}
public int GetNext(ref int value)
{
value = value + 1;
this.val = value;
return this.val;
}
public void Reset(ref int value)
{
// Resetting val.
value = 0;
this.val = value;
}
}
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
int value = 2;
c.Setstart(ref value);
Console.WriteLine(" " + c.GetNext(ref value));
c.Reset(ref value);
Console.WriteLine();
}
}
}
輸出:
val++ 將在返回當前值后遞增,++val 將先遞增,然后返回值,您現在應該得到 3,並使其適當范圍以從外部訪問方法
class Class1 : ISeries {
int val;
public void Setstart (int a) {
val = a;
}
public int GetNext () {
return ++val;
}
public void Reset () {
val = 0;
}
static void Main () {
Class1 c = new Class1();
c.Setstart(2);
Console.WriteLine (c.GetNext());
c.Reset();
Console.WriteLine ("");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.