我有以下靜態屬性定義:類型初始拋出異常,同時訪問靜態屬性
namespace Foo
{
public class Bar
{
private static byte[] aes256Key = null;
internal static byte[] Aes256Key
{
get
{
if (aes256Key != null)
{
return aes256Key;
}
aes256Key = new byte[32];
// Fill in key...
return aes256Key;
}
}
}
}
在另一大類內部的命名空間內,我訪問此屬性:
namespace Foo.Cryptography
{
public class SymmetricCryptography
{
internal static void EncryptFile(
string sourceFile,
string destinationFile)
{
// <snip>
AesManaged aes = new AesManaged();
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Key = Bar.Aes256Key; // Accessing the key here
// <snip>
}
}
}
Foo.Cryptography
使用由可執行控制檯應用程序。當我從構建環境手動運行此控制檯應用程序時,我看不到任何問題。然而,當可執行文件生成過程的範圍內(有可能不同環境中的服務器上)跑,我看到下面的運行時異常:
The type initializer for 'Foo.Bar' threw an exception.
在VS2008的可執行項目具有對Foo
參考該項目定義了Foo
命名空間。
我在這裏做了什麼根本錯誤嗎?什麼可能導致這個?
類型初始值設定項非常好,我喜歡和下一個人一樣使用它們,但是我已經遠離將它們用於除絕對最簡單的任何事情之外的任何東西,因爲它們在炸燬時不會提供非常好的反饋。如果這個異常不在類型初始化器中,你可能會收到一個實際有用的消息。 –
我會說要採取任何類型初始化代碼,並將其推遲到類型初始化後,以便您可以得到一個更好的錯誤消息,但它看起來不像類型初始化程序中的任何事情看起來很多你提供的代碼。 –
在發佈的代碼中沒有類型初始值設定項。沒有需要初始化的字段,並且代碼中未顯示靜態類型初始值設定項。因此,這裏沒有人可以回答爲什麼代碼失敗,因爲你沒有發佈該代碼。請發佈其餘的字段聲明,如果你有它,你的靜態類型初始化器。 –