简体   繁体   中英

Inherited class as reference

I would like to use a function that has a parameter of type A. I would like to pass it a class B which derived from A. But C# does not want to.

class A
{
 int m_a;
}

class B : A
{
 int m_b;
}

void ShowandEditData( ref A _myvar)
{
 ...
}

Now, i would like to do something like this:

B myB = new B();

ShowandEditData(ref myB);

I have tried many things like casting or using the base attribute. I guess I'm doing it wrong.

Is it possible to do that with C#?

--Code Edited due to pseudocode creating confusion . (sorry, first post)

just remove the ref from your method declaration. Like so:

void ShowData(A _myvar)
{
 ...
}

You have to use the ref keywork on the call of method:

ShowData(ref myB);

Actually, classes in is reference values, so you do not need to use ref . Use ref just for value types (structs like int , short , double , decimal , bool , DateTime etc..) when you really want to pass the reference.

In your case you just could use

object ShowData(A _myvar)
{
 ...
}

The ref keyword doesn't support polymorphicism

If you can change the signature of ShowData , then I would suggest you change it like so:

  public A ShowData(A _myvar)
  {
     return new B();  // Or A() or whatever.
  }

And call like so:

B myB = new B();
myB = ShowData(myB);

Alternatively, you'll need to provide overloads of ShowData for both classes:

  public void ShowData(ref A _myvar)
  {
     _myvar = new B();
  }

  public  void ShowData(ref B _myvar)
  {
     _myvar = new B();
  }

Then the compiler can choose the overload:

     A myA = new A();
     B myB = new B();
     ShowData(ref myB);
     ShowData(ref myA);

As an aside, ShowData is not a good name. MutateData sounds more appropriate :-)

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