C#:使派生对象有条件地共享相同的基础对象

C# : make derived object conditionally share same base object

我有一个基 class 由多个派生的 class 继承。我正在构造函数中初始化 base class 的一些属性。有什么方法可以使我的派生对象共享基础 class 属性,而不是为每个派生的 class 对象创建相同的 属性 值。这非常重要,因为一些基本 class 属性 值是由服务生成的,共享这些值可以提高性能。 以下是我要说的内容的简单蓝图:

public class ClassA
{
    //i dont want to use static here as it will be shared for multiple codes
    protected string country { get; set; }
    public ClassA(string code)
    {
        country = CallsomeService(code);
    }
}

public class ClassB : ClassA
{
    public ClassB(string code) : base(code)
    {
        //blah blah
    }

    public void DomeSomethingWithCountry()
    {
        Console.WriteLine($"doing this with {country} in classB");
    }
}

public class ClassC : ClassA
{
    public ClassC(string code) : base(code)
    {
        //blah blah
    }

    public void DomeSomethingWithCountry()
    {
        Console.WriteLine($"doing soemthing else with {country} in classC");
    }
}

现在制作如下对象

     public void test()
        {
            //call service for this
            var classb=new ClassB("1");
            //dont call service for this
            var classc=new ClassC("1");
classb.DomeSomethingWithCountry();
classc.DomeSomethingWithCountry();
            //call service for this as code is different
            var classb1=new ClassB("2");
        }

您可以存储静态调用的结果,而不是值本身。

public class ClassA
{
    static Dictionary<string,string> codeToCountryLookup
         = new Dictionary<string,string>();
    protected string country { get; set; }
    public ClassA(string code)
    {
       if(!codeToCountryLookup.ContainsKey(code))
            codeToCountryLookup.Add(code,CallsomeService(code));
       country = codeToCountryLookup[code];
    }
}

这在任何方面都不是线程安全的,但应该给你一个起点。