如果您的 API 需要静态方法,那么只需将静态方法添加到您的参考程序集中。
引用程序集可能没有实现,因此它只是定义类型,或者它可能包含实现逻辑。
如果您需要特定于平台的逻辑并且仍然希望在您的参考程序集中使用静态实现,那么这是可能的。这方面的一个例子是PCLStorage NuGet package。这有一个静态 FileSystem 类,它有一个名为 Current 的静态属性。
public static class FileSystem
{
static Lazy<IFileSystem> _fileSystem = new Lazy<IFileSystem>(() => CreateFileSystem(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
public static IFileSystem Current
{
get
{
IFileSystem ret = _fileSystem.Value;
if (ret == null)
{
throw new NotImplementedException();
}
return ret;
}
}
static IFileSystem CreateFileSystem()
{
return null;
}
}
所以你的参考程序集可以定义一个静态类和静态属性,甚至是一个没有实现的静态方法。 PCLStorage 的 FileSystem 类在其引用程序集中有一个私有静态 CreateFileSystem 方法:
然后在您的平台特定程序集中,您的 CreateFileSystem 创建自己的实现 IFileSystem 接口的类。在您的情况下,静态方法可以是公共的而不是私有的。
PCLStorage 项目使用条件定义的代码来创建不同的平台特定和引用程序集:
static IFileSystem CreateFileSystem()
{
#if NETFX_CORE || WINDOWS_PHONE
return new WinRTFileSystem();
#elif SILVERLIGHT
return new IsoStoreFileSystem();
#elif FILE_SYSTEM
return new DesktopFileSystem();
#else
return null;
#endif
}
如果您的程序集的所有名称和版本对于所有平台(包括参考程序集)都相同,则这一切都有效。这是 Paul Betts 在Bait and Switch PCL trick 上的帖子中讨论的bait and switch trick。在 Paul Betts 示例中,可移植类库 (PCL) 被用作参考程序集,他展示了另一种非常相似的方法,即在参考程序集类中使用静态方法并在另一个程序集中使用特定于平台的实现。