【发布时间】:2021-10-01 17:36:59
【问题描述】:
我有一个基类和两个派生类:
public class base1
{
public int property1;
}
public class child1 : base1
{
public int property2;
}
public class child2 : base1
{
public int property3;
}
当我像这样分配newProp 变量时:
int i = 2;
base1 newProp = (i == 0 ? new child1
{
property1 = 1,
property2 = 3
} : null);
它工作正常,newProp 类型更改为 child1 类类型,
但我尝试做的是这样的:
int i = 2;
base1 newProp = (i == 0 ? new child1
{
property1 = 1,
property2 = 3
} : new child2
{
property1 = 4,
property3 = 6
});
但我收到此错误
Type of conditional expression cannot be determined because there is no implicit conversion between `class1` and `class2`
有什么办法吗?
【问题讨论】:
-
我认为你应该使用常规的 if else 语句而不是使用内联运算符
-
您的代码甚至无法编译。
-
在修正语法规则后,一切都会编译,不需要这个问题。
-
这个问题与那些仍然必须使用 C#9.0 之前的 C# 版本的人有关
标签: c# inheritance derived-class base-class