如何在子类中创建动态类型并分配它?

时间:2017-03-02 08:57:21

标签: c#

首先,我有一个父类,如:

Father

这是继承自Method_A的两个类。但Child_A仅属于Child_B而非public class Child_A : Father { // skip ... public void Method_A { ... } } public class Child_B : Father { // skip ... }

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.
    }
  }

最后,我尝试创建一个可以动态分配给

的变量
var

如下错误:

  

键入'父亲'不包含' Method_A'的定义没有扩展方法' Method_A'类型'父亲'可以找到。你错过了装配参考吗?

我为dynamicObject尝试了var类型,但我们必须在本地范围内设置public class MyClass { public var dynamicObject; // It's not allow. // ... } 类型。

SET TERM ^ ;

create or alter procedure GET_DIGIT_ONLY (
    IPARAM varchar(32))
returns (
    OPARAM varchar(32))
as
declare variable I integer;
begin
  oparam = '';
  i = 1;
  while (i <= char_length(:iparam)) do
  begin
    if (substring(:iparam from i for 1) similar to '[0123456789]')  then
      oparam = :oparam || (substring(:iparam from i for 1));
    i = :i + 1;
  end
  suspend;
end^

SET TERM ; ^

3 个答案:

答案 0 :(得分:3)

使用强制转换来检查dynamicObject的类型:

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

或使用C# 6和Null条件运算符:

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和模式匹配,如@Zbigniew建议:

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

答案 1 :(得分:0)

尝试替换

dynamicObject.Method_A();

通过

((Child_A)dynamicObject).Method_A();

答案 2 :(得分:0)

我认为,在界面上使用Method_A更有意义。虽然方法和类的数量增加,但管理起来会更容易

    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();
        }
    }