【问题标题】:A Beginner Puzzle of Static and Non-Static Classes in OOP ( C# )OOP(C#)中静态和非静态类的初学者难题
【发布时间】:2012-01-20 15:08:58
【问题描述】:

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

  1. Dictionary 中删除 static 关键字 LiveMembers 类中。
  2. 不要使用new Members();Check(...) 方法中创建实例。

因此,根据这些规则,您必须从其他类调用 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;
        }
    }
}

他说,“有办法做到这一点。”,但我找不到,我不相信真的有。你有什么意见?

更新/回答: 我在 Daniel Hilgarth 的帮助下解决了这个问题……就是这样;


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);

【问题讨论】:

  • 我能想到的只有反射......

标签: oop class c#-4.0 static non-static


【解决方案1】:

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

Members.Instance.Live.TryGetValue(signatureFromRequest, out userId);

注意.Instance 部分。

请参阅here 了解实现单例的几种方法。

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

我想最好直接问你的同事他的意思。

【讨论】:

  • 有效!完美...非常感谢丹尼尔。我将阅读您通过答案提供的文章链接。但是,请-快点;你能用几句话解释我的魔法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2011-01-17
  • 2012-12-09
  • 1970-01-01
  • 2014-01-22
  • 2013-02-08
  • 1970-01-01
相关资源
最近更新 更多