在程序集之间交换任意对象

Exchange arbitrary objects between assemblies

在我的 C# 应用程序中,我将多个程序集加载到一个应用程序中。为了在程序集之间快速交换对象,我在常用的 .NET 命名空间中寻找现有的 class,我可以 "abuse" 来交换通用对象。

我在考虑 System.ConfigurationManager.AppSettings,但这个只支持字符串。有没有 object 类型的?

我知道这是在程序集之间交换数据的糟糕解决方案,但我现在不能更改接口。

我假设你想这样做:

// Assembly 1
SomeSuperGlobal.Set("someKey", new Foo { Bar = "baz" });

// Assembly 2
var foo = SomeSuperGlobal.Get("someKey");

首先发出警告,你的设计很糟糕。你 should not let your code rely on global state,这些做法至少从六十年代开始就被废除了。不要这样做,彻底考虑重新设计应用程序。

也就是说,你可以 use named data slots:

// Assembly 1
LocalDataStoreSlot dataSlot =  System.Threading.Thread.AllocateNamedDataSlot("someKey");
System.Threading.Thread.SetData(dataSlot, new Foo { Bar = "baz" });

// Assembly 2
LocalDataStoreSlot dataSlot = System.Threading.Thread.GetNamedDataSlot("someKey");
var foo = System.Threading.Thread.GetData(dataSlot);

务必阅读Thread.AllocateNamedDataSlot()'s documentation