简体   繁体   中英

How to inherit from base class

Hi My code is as follows

public partial class Class1:InheritBase1
{

 public Class1()
 { 
   //Access table1 here
 }

}

public class InheritBase2 
{
     protected DataTable table1{get;set;}
}

I need to access table1 from InheritBase2 class to my class.

As C# doesn't allow multiple inheritance what are the possible ways to achieve this ?

Thank's all.

You could easily solve this using composition instead of inheritance.

Say there's a class A and a class B . A has a B .

public class A
{
    public B AssociatedB { get; set; }
}

Why...?

could you please elaborate – kyle

In object-oriented programming there're two approaches to create relationships between objects. Either of them are necessarily hierarchical .

If you end up thinking some object is something, we'll be talking about inheritance . For example, a cat is an animal . That is, a class cat derives from animal .

In the other hand, if you end up thinking some object has a X thing, we'll be talking about composition . For example, a car has an engine.

At the end of the day, if you are using inheritance in order to share a reference to a DataTable , I really encourage you to use composition instead, because your class has a DataTable :

public class A 
{
    public DataTable Table { get; set; }
}

public class B 
{
    public DataTable Table { get; set; }
}

DataTable someTable = new DataTable();

// Both class instances share the same DataTable
// because you set the same object to both
// class properties
A someA = new A();
someA.Table = someTable;

B someB = new B();
someB.Table = someTable;

You can benefit form the composition.

class A : B {

}

can be replaced as

class A {
   B b 
}

If you want that A and B can be used in the same contenxt you need to intruduce a interface.

The interface allow you to define abstract functionality and have various implementations for it.

interface ISampleInterface
{
    void SampleMethod();
}

In case when we have

class B : ISampleInterface
{
     void SampleMethod() { 
         //Do some action
     }
}

Now your class A can or inherit form B in odrder to access to sample method or use composition.

class A : ISampleInterface {

   B b; 

   void SampleMethod() { 
         b.SampleMethod();
     }

}

Then i code you can use this like

 ISampleInterface  sa = new A(); 
 ISampleInterface  sb = new B();  

  sa.SampleMethod(); //Call B through A
  sb.SampleMethod(); //Call B

This is only bired description for more you should follow a tutorial about Object Oriented Programming.

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