最安全的方法(即在您的应用程序中不出错的最简单方法)可能如下。
制作一个抽象您对 TFS 使用的接口,例如:
interface ITfs
{
bool checkout(string filename);
}
编写一个使用 TFS 实现此接口的类:
class Tfs : ITfs
{
public bool checkout(string filename)
{
... code here which uses the TFS assembly ...
}
}
编写另一个不使用 TFS 实现此接口的类:
class NoTfs : ITfs
{
public bool checkout(string filename)
{
//TFS not installed so checking out is impossible
return false;
}
}
在某处有一个单身人士:
static class TfsFactory
{
public static ITfs instance;
static TfsFactory()
{
... code here to set the instance
either to an instance of the Tfs class
or to an instance of the NoTfs class ...
}
}
现在只有一个地方需要小心(即 TfsFactory 构造函数);您的其余代码可以调用 TfsFactory.instance 的 ITfs 方法,而无需知道是否安装了 TFS。
在下面回答最近的cmets:
根据我的测试(我不知道这是否是“定义的行为”),当您(一旦)调用依赖于缺少程序集的方法时,就会引发异常。因此,将依赖于缺失程序集的代码封装在程序集中的至少一个单独的方法(或单独的类)中非常重要。
例如,如果缺少 Talk 程序集,则不会加载以下内容:
using System;
using OptionalLibrary;
namespace TestReferences
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "1") {
Talk talk = new Talk();
Console.WriteLine(talk.sayHello() + " " + talk.sayWorld() + "!");
} else {
Console.WriteLine("2 Hello World!");
}
}
}
}
将加载以下内容:
using System;
using OptionalLibrary;
namespace TestReferences
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "1") {
foo();
} else {
Console.WriteLine("2 Hello World!");
}
}
static void foo()
{
Talk talk = new Talk();
Console.WriteLine(talk.sayHello() + " " + talk.sayWorld() + "!");
}
}
}
这些是测试结果(在 Windows 上使用 MSVC# 2010 和 .NET):
C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>TestReferences.exe
2 Hello World!
C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>TestReferences.exe 1
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'OptionalLibrary, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
at TestReferences.MainClass.foo()
at TestReferences.MainClass.Main(String[] args) in C:\github\TestReferences\TestReferences\TestReferences\Program.cs:
line 11
C:\github\TestReferences\TestReferences\TestReferences\bin\Debug>