How to create a dynamic type in the children class and assign it?

First I have a parent class:

public class Father {
  // skip ...
}

And these are two classes that inherit from Father. But it Method_Abelongs only Child_Ainstead Child_B.

public class Child_A : Father {
  // skip ...

  public void Method_A { ... }
}


public class Child_B : Father {
  // skip ...
}

Finally, I am trying to create a variable that can be dynamically assigned

public class MyClass {
  public Father dynamicObject;

  public void MyMethod {
    dynamicObject = new Child_A(); // Sometimes will be `Child_B`.

    if (...) {                     // only `Child_A` can pass, I promise
      dynamicObject.Method_A();    // Error here.
    }
  }

The error as shown below:

The type Father does not contain a definition for Method_A, and the extension method Method_A of type Father cannot be found. Are you missing an assembly link?


I tried type varfor dynamicObject, but we have to set the type varin local area.

public class MyClass {
  public var dynamicObject; // It not allow.
  // ...
}
+4
source share
3 answers

Use cast to check type dynamicObject:

Child_A childA = dynamicObject as Child_A;
if (childA != null) 
{               
    childA.Method_A(); 
}

C# 6 :

Child_A childA = dynamicObject as Child_A;             
childA?.Method_A(); 

is (Child_A), .

if (dynamicObject is Child_A) {
   ((Child_A)dynamicObject).Method_A();
}

C#7 Pattern Matching, @Zbigniew, :

if (dynamicObject is Child_A child) {
   child.Method_A();
}
+3

dynamicObject.Method_A();

((Child_A)dynamicObject).Method_A();
0

i, it makes sense to use Method_A on the interface. while the number of methods and classes increases, it will be easier to manage

    public class Father { }
    public class Child_A : Father, IMethodOwner { public void Method_A() { }}
    public class Child_B : Father{ }
    public interface IMethodOwner { void Method_A(); }
    public class MyClass
    {
        public Father dynamicObject;
        public void MyMethod() {
            var obj = dynamicObject as IMethodOwner;
            if(obj != null)
                obj.Method_A();
        }
    }
0
source

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


All Articles