Trying to understand the essence of limitations - am I on the right track?

I think that finally I got a sense of limitations, but still a little confused. Can someone tell me if the following is correct?

Basically, if you inherit a class, you can make sure that the inherited class also inherits from some other class or other interface.

This is confusing because you probably know that you only want to inherit from a class that had what you wanted, but I think that using generics you can get a compilation error at some point and not know that the problem is actually related to the fact that some class is not inherited elsewhere, and you may get errors that make sense if you add restrictions to the correct areas.

It makes sense? Am I on the right track?

+3
source share
4 answers

I do not think the point of limitation (but I could be wrong).

As I understand it, restrictions do not have much to do with inheritance as such. What you are really doing is a type restriction that can be used if you use (instantiate) a class with type arguments.

Classes with type arguments are similar to Mad-Libs, and the restrictions are similar to the instructions that appear under spaces:

"Bob loves ______ with friends every night." (what is madlib)

"Bob loves every night (with a verb) ___ with his friends" (maslib with instructions).

Check this:

//class with type arguments
public class MadLib<W> {
   public void addWord(W word) {
      System.Console.WriteLine("bob likes to " + word + " with his friends");
   }
}


//class with type arguments and contraints (note i'm not inheriting nothin)
public class MadLib<W> where W:Verb{
   public void addWord(W word) {
      System.Console.WriteLine("bob likes to " + word + " with his friends");
   }
}
+4
source

. , / .

, :

class GenericDisposableHandler<T>
{
    public void DoOperationOnT(T someVariable)
    {
       // can't really do much with T since its just an object type
    }
}

, T -, IDisposable, :

class GenericDisposableHandler<T> where T : IDiposable
{
    public void DoOperationOnT(T someVariable)
    {
        // Now you can treat T as IDisposable
        someVariable.Dispose();
    }
}

, .

+4

. , ( ).

, , "" , undefined/ T, - T. WHICH Types T , /

 //Define the generic here, with arbitrary type T 
 public class MyClass<T> where T: SomeOtherClass
  {
    // template/pattern methods, proerpties, fields, etc.
  }

"DerivedClass"

public MyClass<DerivedClass> myC = new MyClass<DerivedClass> ();

which will succeed if and only if DerivedClass inherits from SomeOtherClass

+2
source

You can inherit only one class, however you can implement several interfaces. Inheritance means that your class receives (inherits) all the properties and methods that the base class indicates. As long as they are not marked as private, the inheriting class can call these methods as its own.

0
source

Source: https://habr.com/ru/post/1717466/


All Articles