Is static context always single in C#?

前端 未结 3 499
星月不相逢
星月不相逢 2020-12-24 10:53

I have a library that has a static field inside. I want to create an app and reference this library so I\'d have two instances of this static field. .Net runtime does not al

相关标签:
3条回答
  • 2020-12-24 11:18

    That's not as crazy as you think. In fact, you can achieve this using AppDomains.

    Each AppDomain has its own storage location for static variables. So you can just create a second AppDomain in your process, and communicate between them using an object that inherits from MarshalByRefObject like in this MSDN example.

    0 讨论(0)
  • 2020-12-24 11:18

    While Lucas' suggestion on AppDomains would work, alternatively you could create this effect using generics, as a class with different generic type arguments is treated as a different class, and therefore has its own static fields.

    public class SomeClass<T>
    {
        public static string SomeField;
    }
    

    Then:

    SomeClass<int>.SomeField = "A";
    SomeClass<string>.SomeField = "B";
    
    Console.WriteLine(SomeClass<int>.SomeField);    // A
    Console.WriteLine(SomeClass<string>.SomeField); // B
    

    For example, the SomeClass<int> would be set in the library, whereas the SomeClass<string> would be your copy. Of course this would only work if you could change the library, or the library already used generics.

    0 讨论(0)
  • 2020-12-24 11:21

    Both suggestions should work, but they are all terrific concerning architecture.

    I a not aware about the context, but in your case is it possible to just create an aggregation class with a new property that is not static and just have two instances. This sound like a better way for me.

    Everytime I have smart code, an alert starts in my head. Smart code is always too clever for a developer.

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