简体   繁体   中英

Why will my interface not implement a public method?

Why will my interface not import into my class? I just want to test some interfaces and need to have the one method extended into my class that implements my interface. This I thought would be simple but it is throwing me an error which I will list at the bottom. My method is public and it is throwing me and error. In fact I took the public keyword away and it is still throwing me an error.

Is there a short cut key to import all of the methods into a class.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FlowControl
{
    public abstract class Grades : iBase, iFoot
    {
        public abstract void AddGrade(float grade);

        public abstract void ComputeStatistics();

        public void WriteGrades(string t)
        {
        }

        public int AddTwo(int a, int b)
        {
            return 0; 
        }

        void findYourScore() { }
    }

    public interface iBase 
    {
       public void findYourScore();
    }

    public interface iFoot 
    { 
    }
}

But I get this error:

The modifier 'public' is not valid for this item

You can't specify access modifiers on interface methods, properties, events, or indexers. The interface itself is marked public, therefore all of its members are also implicitly public. However, you will have to specify an access modifier where you're implementing the method (unless you're writing an explicit interface member implementation).

For example:

public abstract class Grades : iBase, iFoot
{
    ...
    public void findYourScore() { }
}

public interface iBase 
{
    void findYourScore();
}

Further Reading

You can't specify the access modifiers inside of interface.You just need to specify signature of the method

public interface iBase 
{
    void findYourScore();
}

From documentation :

Interfaces can contain methods, properties, events, indexers, or any combination of those four member types. An interface can't contain constants, fields, operators, instance constructors, destructors, or types. Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.

It is as simple as

public interface iBase 
{
   void findYourScore();
}

Interface members don't need access qualifiers. public is then not valid in this context, as the compiler says.

Interfaces do not specify the protection levels or methods and do not implement them either. Removes the public / private piece and your code will work fine. Classes which implement an interface determine what the access level is. If you need to specify access level use an abstract class instead of an interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM