Is a static context always the same in C #?

I have a library that has a static field in it. I want to create an application and reference this library so that I have two instances of this static field .. Net runtime does not allow me to reference the same library twice, but I wonder if this restriction can be overcome?

I am not allowed to modify the library, but I can copy / rename it.

+54
c #
Jan 30 '15 at 11:58
source share
3 answers

This is not as crazy as you think. In fact, you can achieve this using AppDomains .

Each AppDomain has its own repository for static variables. That way, you can simply create a second AppDomain in your process and exchange data between them using an object that inherits from MarshalByRefObject , as in this MSDN example .

+84
Jan 30 '15 at 12:01
source share

While Lucas's suggestion in AppDomains will work, alternatively you can create this effect using generics, since a class with different arguments of a general type is considered as another 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, SomeClass<int> will be installed in the library, while SomeClass<string> will be your copy. Of course, this will only work if you can change the library or the library that already used the generic files.

+57
Jan 30 '15 at 12:06
source share

Both suggestions should work, but they are all amazingly architecture related.

I do not know about the context, but in your case, you can simply create an aggregation class with a new property that is not static and has only two instances. That sounds like the best way for me.

Every time I have a smart code, a warning appears in my head. Smart code is always too smart for the developer.

+1
Feb 13 '15 at 10:47
source share



All Articles