Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
OOP(C#)中静态和非静态类的初学者难题_Oop_Class_C# 4.0_Static_Non Static - Fatal编程技术网

OOP(C#)中静态和非静态类的初学者难题

OOP(C#)中静态和非静态类的初学者难题,oop,class,c#-4.0,static,non-static,Oop,Class,C# 4.0,Static,Non Static,我的一个朋友(工作中)问了我一个问题 从成员类的字典活动中删除静态关键字 不要使用新成员()在检查(…)方法中创建实例 因此,根据这些规则,您必须为来自其他类的callLive做些什么,例如: Members.Live.TryGetValue(signatureFromRequest, out userId); 我有这个 using System; using System.Collections.Generic; namespace Webbing.Session { public

我的一个朋友(工作中)问了我一个问题

  • 成员
    类的
    字典
    活动
    中删除
    静态
    关键字
  • 不要使用
    新成员()
    检查(…)
    方法中创建实例
  • 因此,根据这些规则,您必须为来自其他类的call
    Live
    做些什么,例如:

    Members.Live.TryGetValue(signatureFromRequest, out userId);
    
    我有这个

    using System;
    using System.Collections.Generic;
    namespace Webbing.Session
    {
        public class Members
        {
            // THAT Dictionary Live was a static... public static Dictionary...
            public Dictionary Guid, int> Live = new Dictionary Guid,int>();
        }
    }
    
    这是:

    using System;
    using WcfService.Session;
    
    namespace Webbing.BusinessDb
    {
        public class Signature
        {
            public static bool Check(Guid signatureFromRequest)
            {
                bool result = false;
    
                int userId;
    
                Members checker = new Members(); // <--------- don't use this
                checker.Live.TryGetValue(signatureFromRequest, out userId);
    
                if (userId != 0)
                {
                    result = true;
                }
    
                return result;
            }
        }
    }
    
    }


    用法:Members.Instance.Live.TryGetValue(signatureFromRequest,out userId)

    无法使用您提供的确切语法。
    一种可能是单身,但看起来是这样的:

    请注意
    .Instance
    部分

    有关实现单例的几种方法,请参见

    如您所见,现在
    Live
    属性不再是静态的,但是新属性
    实例


    我想最好只是问问你的同事他是什么意思。

    我唯一能想到的就是反思……这很有效!太完美了。。。非常感谢你,丹尼尔。我将阅读你通过回答给出的文章链接。但是,请——快点;你能用几句话给我解释一下魔法吗?
    
    using System;
    using System.Collections.Generic;

    namespace Webbing.Session { public class Members { // Guid, userId public Dictionary Guid, int> Live = new Dictionary Guid,int>();

        private static readonly Members __instance = new Members();
    
        public static Members Instance
        {
            get
            {
                return __instance;
            }
        }
    }
    
    Members.Instance.Live.TryGetValue(signatureFromRequest, out userId);