C#非静态类中的静态属性作为此类主对象的指示符

时间:2017-12-05 21:09:11

标签: c# static coding-style

我有类Important,并且创建了这个类的一些对象。我想让用户选择这个类的主要对象。看看下面的代码:

public class Program
{
    public static void Main(string[] args)
    {
       Important imp1 = new Important("Important 1");
       Important imp2 = new Important("Important 2");
       Important imp3 = new Important("Important 3");

       imp2.SetMostImportant();

       Console.Write(Important.MostImportant.Name);
    }

    public class Important
    {
        public Important(string name)
        {
            Name = name;
            if(MostImportant == null)
                SetMostImportant();
        }

        public string Name { get; private set; }
        public static Important MostImportant { get; private set; }

        public void SetMostImportant()
        {
            MostImportant = this;
        }
    }
 }

这是好的解决方案吗?如果没有,请告诉我为什么不。

之前,为了实现这种事情,我刚刚创建了名为eg的boolean字段IsMainObject,当我想要更改主对象时,我迭代了特定类的所有对象(或对象组),除了我想成为main的元素,并将boolean更改为false,在我的新候选中我只将flag设置为true 。示例如下:

public class Program
{
    public static void Main(string[] args)
    {
       Important imp1 = new Important("Important 1");
       Important imp2 = new Important("Important 2");
       Important imp3 = new Important("Important 3");
       List<Important> list = new List<Important> { imp1, imp2, imp3 };

       foreach(var item in list.Where(x => x.Name != "Important 2"))
       {
           item.SetMostImportant(false);
       }

       imp2.SetMostImportant(true);
       Console.Write(list.FirstOrDefault(x => x.MostImportant == true).Name);
    }

    public class Important
    {
        public Important(string name)
        {
            Name = name;
        }

        public string Name { get; private set; }
        public bool MostImportant { get; private set; }

        public void SetMostImportant(bool val)
        {
            MostImportant = val;
        }
    }
}

我不喜欢这个解决方案,因为:

  1. 我不知道MostImportant是否适用于多个没有迭代的对象。
  2. 我需要编写额外代码来处理更多案例。
  3. 我没有可能总是遍历特定类的所有实例(组并不总是足够)。
  4. ......还有更多,但你明白了。

1 个答案:

答案 0 :(得分:1)

ul. Niecała 10, 05-800 Pruszków

是一个很好的解决方案,比

好多了
public static Important MostImportant { get; private set; }

在实现“singleton”类时,有一个类型的静态属性并不罕见。我编写的代码类似于:

public bool MostImportant { get; private set; }
相关问题