【问题标题】:Using object field as function parameter other field [duplicate]使用对象字段作为函数参数其他字段[重复]
【发布时间】:2021-01-02 16:54:16
【问题描述】:

是否可以使用新的对象字段作为函数参数其他字段(在同一个对象初始化中)?

List<Reservations> reservations = new List<Reservations>()
 {
  new Reservations{title="Grooming", className=checkColor(title)},
 };

public string checkColor(string title)
{
 ...
}         

【问题讨论】:

  • 是的,你可以做到
  • 我不这么认为。你必须使用 className=checkColor("Grooming") 为什么你没有立即检查它而不是浪费其他人的时间?
  • 不,您不能从该对象的对象初始化程序中引用该对象。如果您需要运行其他逻辑,则应考虑使用构造函数或工厂方法。

标签: c#


【解决方案1】:

您的代码的当前设计是不可能的。原因是,在对象完全构造之前,您不能在另一个字段中引用对象的 1 个字段。这与我们在声明为类级别变量时不能在另一个字段值中使用 1 个字段值的原因相同。

但是,有一些方法可以实现,你想要什么。

选项 1:

const string titleText = "Grooming";
List<Reservations> reservations = new List<Reservations>()
{
    new Reservations{title=titleText, className=checkColor(titleText)},
};

private static string checkColor(string title)
{
 ...
}

选项 2:

    class Consumer
    {
        List<Reservations> reservations = new List<Reservations>()
        {
            new Reservations{title="Grooming"}
        };
    }

    class Reservations
    {
        string _title;

        public string title
        {
            get
            {
                return _title;
            }

            set
            {
                _title = value;
                className = checkColor(title);
            }
        }

        public string className;

        private string checkColor(string title)
        {
            return "";
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-18
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多