Is there an inheritance method in C #

I am wondering if there is any function like inheritance method and not whole class inheritance, let me explain in detail what I'm trying to explain:

class a {
   public void GetA(){
     // some logic here
}
}

class b {
    public void GetB() : new Class().GetA()
}

I know this looks weird, but I read how to do delegation in an object composition template, and for some reason I was thinking about this template.

+3
source share
7 answers

If you just want to call GetA () inside GetB () but don’t want to define or explicitly refer to an instance of class a in GetB (), you can pass GetA () as a delegate.

# , Func. .

    class a
    {
        public void GetA()
        {
            Console.WriteLine("Hello World!");
        }
    }

    class b
    {
        // No explicit reference to class a of any kind.
        public void GetB(Action action)
        {
            action();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new a();
            var b = new b();

            b.GetB(a.GetA);
        }
    }
+4

- b, class a, GetB() - a.GetA(). :

class a {
   public void GetA(){
     // some logic here
   }
}

class b {
    private a _a=new a();

    public void GetB()
    {
         _a.GetA();
    } 
}

, - GetB , GetB().

+4

, , , # "" ( ), :

class Animal {
    public string Species { get; set; }

    public Animal(string species) {
        Species = species;
    }
}

class Human : Animal {
    public string Name { get; set; }

    public Human(string name) : base("Homo sapien") {
        Name = name;
    }
}

: Human Animal, - . , .

+3

. , b.GetB a.GetA, a a.GetA.

+1

, ClassA ClassB, . @Ash:

public class ClassB
{
    private readonly ClassA _a;

    public b(ClassA a)
    {
        _a = a;
    }

    public void GetB()
    {
        _a.GetA();

        // Other logic
    }
}
0
public class Article
{

 public object AddOrUpdate(params object[] paras){

   return null;

  }

}

public class Test:Article
{

 public new object AddOrUpdate(params object[] paras){

   //do your logic......

    return base.AddOrUpdate(paras);

 }


}

? , BASE.

, .

, .

0

If GetA () is changed to a static method, you can simply call it in the GetB () function:

class a { 
   public static void GetA() { 
     // some logic here 
   } 
} 

class b { 
    public void GetB() {
      a.GetA();
    }
} 

If GetA () is not static, this makes no sense, because by definition GetA () requires an object context (for example, the invisible pointer "this"). You cannot pass an instance of object B to class A, because class A knows nothing about class B.

What are you really trying to do?

0
source

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


All Articles