最安全的方式(即在应用程序中避免错误的最简单方法)可能如下所示。
创建一个抽象您使用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)
{
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。
回答以下最近的评论:
根据我的测试(我不知道这是否是“定义行为”),当您调用依赖于缺失程序集的方法时,会抛出异常。因此,重要的是将依赖于缺失程序集的代码封装在至少一个单独的方法(或单独的类)中。在您的程序集中。
例如,如果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() + "!");
}
}
}
以下是使用MSVC# 2010和.NET在Windows上的测试结果:
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>