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

Unn*_*nie 2 c# oop multiple-inheritance

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

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在制作如下的对象

     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");
        }
Run Code Online (Sandbox Code Playgroud)

Jam*_*iec 6

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

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

这绝不是线程安全的,但应该给你一个开始的地方.