繁体   English   中英

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

[英]C# Static property in non-static class as indicator of main object of this class

我有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;
        }
    }
 }

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

以前,为了实现这种目的,我刚刚创建了一个名为IsMainObject的布尔字段,并且当我想更改主对象时,我遍历了特定类的所有对象(或对象组),除了我想成为主元素的元素外,并且将布尔值更改为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. 我没有机会总是遍历特定类的所有实例(组并不总是足够的)。

...还有更多,但是你明白了。

public static Important MostImportant { get; private set; }

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

public bool MostImportant { get; private set; }

在实现“单例”类时,具有其内部类型的静态属性并不少见。 我编写了类似于以下代码:

class MyClass
{
    public static MyClass Instance { get; private set; }
    public MyClass()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            throw new Exception("MyClass already instantiated.");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM