Question

My generic class is defined as follows:

public class MySortedList<TKey, TItem> where TItem : MyClass<TKey>

In one of class' methods I create an instance of TItem and call one of its protected methods:

TItemInstance.MyMethod();

Here I get the error that

MyMethod is inaccessible due to its protection level

What level of protection should MyMethod have?
Thank You.

Était-ce utile?

La solution

Methods declared as protected can only be used in the classes and their subclasses.

If you want to use method outside of the class, you should declare it as public:

public void MyMethod()

or, if the caller is defined in the same assembly, internal:

internal void MyMethod()

Autres conseils

Because MySortedList isn't derived from TItem then you will need to make the method in question public for it to be callable from MySortedList.

You can only call protected methods from the defining class or one of its derived classes.

See the Microsoft documentation for more details.

The class in which you have MyMethod function must be declare as public because here you want to use that method outside the class. So it should be public.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top