Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
父通配符变量多态设置为其任何子类型c#_C# - Fatal编程技术网

父通配符变量多态设置为其任何子类型c#

父通配符变量多态设置为其任何子类型c#,c#,C#,我想将一个变量设置为它的任何子类型。用代码更好地解释 如果我有: public class B : A { public int bCounter; } public class C : A { public int cCounter; } 我想: A myVarible; if (someCondition) { A = new B(); A.bCounter++; } if (someOtherCondition) { A = new C();

我想将一个变量设置为它的任何子类型。用代码更好地解释

如果我有:

public class B : A {
    public int bCounter;
}

public class C : A {
    public int cCounter;
}
我想:

A myVarible;
if (someCondition) {
    A = new B();
    A.bCounter++;
}
if (someOtherCondition) {
    A = new C();
    A.cCounter++;
}
将父项设置为通配符变量,而不是设置所有可能的子项类型。
这种快捷方式或类似方式是否可行?

由于变量
myVariable
的类型为
A
,因此无法使用派生类型成员对其进行寻址。(
A
不知道
B
成员。)根据您的情况,有多种选择

如果对
A
没有控制权,或者业务逻辑需要它,则可能需要重新声明变量以使其进行编译

if (someCondition) {
    var b = new B();
    b.bCounter++;
    myVariable = b;
}

if (someOtherCondition) {
    var c = new B();
    c.cCounter++;
    myVariable = c;
}

如果这样做有意义,您可以在
a
上生成一个方法,以
IncrementCounter()

这反过来又可以简化业务逻辑:

A myVariable;
if (someCondition) {
    myVariable = new B();
}
if (someOtherCondition) {
    myVariable = new C();
}

myVariable.IncrementCounter();

您的示例可能是
myVarible=new B();myVarible.bCounter++感谢您的回答,这两个声明
var b=new b()
var c=new B()是我想要避免的,对于任何可能的子类型赋值都只有一个声明。看来这是不可能的。谢谢
A myVariable;
if (someCondition) {
    myVariable = new B();
}
if (someOtherCondition) {
    myVariable = new C();
}

myVariable.IncrementCounter();