Global instances of class

后端 未结 1 626
一生所求
一生所求 2021-01-01 03:43

Still trying to get to know C# (Mostly worked with C). I have a class \"Device\" and would like to create an instance of the class, but would also like access to the instanc

相关标签:
1条回答
  • 2021-01-01 04:18

    Create a new instance and assign it to a static property or field:

    public class AnyClass
    {
        public static readonly Device ThisFieldCanBeReachedFromAnywhere = new Device();
    }
    

    Note that the class AnyClass doesn't have to be static (that would however mean that all members must be static).

    Also note that the readonly keyword isn't required, it is just good practice for singletons (like Mark suggested in his comment).

    0 讨论(0)
提交回复
热议问题