首页 > 解决方案 > 根据构造函数中的条件向基构造函数传递不同的值

问题描述

我有一个构造函数如下

public class Person : Animal
{
    public Person(Settings settings) : base(settings.ActionProperty1)
    {

    }
}

public class Animal
{
    public Animal(Action a)
    {

    }
}

public class Settings
    {
        public bool Flag { get; set; }

        public Action ActionProperty1 { get; set; }

        public Action ActionProperty2 { get; set; }
    }

如何根据某些条件向基本构造函数传递不同的值。即类似于以下内容。

public Person(Settings settings) : base(settings.flag ? settings.ActionProperty1 : settings.ActionProperty2)
{

}

以上给了我一个编译错误:CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'

此外,我无法通过在基类中添加属性设置器来解决此问题。我需要在对基础的构造函数调用中执行此操作

编辑:答案在此处链接的第二个副本中提供。无法确定条件表达式的类型 (Func)我不得不将可选参数之一强制转换为操作。谢谢

标签: c#oopconstructor

解决方案


推荐阅读